-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
listing-8.3.js
61 lines (54 loc) · 1.66 KB
/
listing-8.3.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"use strict";
const MongoClient = require('mongodb').MongoClient;
const hostName = "mongodb://127.0.0.1:7000";
const databaseName = "weather_stations";
const collectionName = "daily_readings";
//
// Open the connection to the database.
//
function openDatabase () {
return MongoClient.connect(hostName)
.then(client => {
const db = client.db(databaseName);
const collection = db.collection(collectionName);
return {
collection: collection,
close: () => {
return client.close();
},
};
});
};
let numRecords = 0;
//
// Read the entire database, document by document using a database cursor.
//
function readDatabase (cursor) {
return cursor.next()
.then(record => {
if (record) {
// Found another record.
// Put your code here for processing the record.
console.log(record);
++numRecords;
// Read the entire database using an asynchronous recursive traversal.
return readDatabase(cursor);
}
else {
// No more records.
}
});
};
openDatabase()
.then(db => {
const databaseCursor = db.collection.find();
return readDatabase(databaseCursor) // NOTE: You could use a query here.
.then(() => db.close()); // Close database when done.
})
.then(() => {
console.log("Displayed " + numRecords + " records.");
})
.catch(err => {
console.error("An error occurred reading the database.");
console.error(err);
});