forked from lighthouse-labs/tweeter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_example.js
41 lines (31 loc) · 985 Bytes
/
mongo_example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"use strict";
const {MongoClient} = require("mongodb");
const MONGODB_URI = "mongodb://localhost:27017/tweeter";
MongoClient.connect(MONGODB_URI, (err, db) => {
if (err) {
console.error(`Failed to connect: ${MONGODB_URI}`);
throw err;
}
// We have a connection to the "tweeter" db, starting here.
console.log(`Connected to mongodb: ${MONGODB_URI}`);
// ==> Refactored and wrapped as new, tweet-specific function:
function getTweets(callback) {
db.collection("tweets").find().toArray((err, tweets) => {
if (err) {
return callback(err);
}
callback(null, tweets);
});
}
// ==> Later it can be invoked. Remember even if you pass
// `getTweets` to another scope, it still has closure over
// `db`, so it will still work. Yay!
getTweets((err, tweets) => {
if (err) throw err;
console.log("Logging each tweet:");
for (let tweet of tweets) {
console.log(tweet);
}
db.close();
});
});