This repository was archived by the owner on Sep 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.js
113 lines (85 loc) · 2.73 KB
/
mongo.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
exports.saveOne = saveOne;
exports.fetchLast10 = fetchLast10;
var MongoClient = require('mongodb');
var request = require('request-promise');
// save one data object to mongo db
function saveOne(dbUrl, collectionName, data) {
var context = {
DB_URL: dbUrl,
DATA: data,
COLLECTION: collectionName
};
// cascade of all needed promises
return openDatabaseConnection(context)
.then(saveData)
.then(closeDatabaseConnection);
}
// fetch last 10 saved documents
function fetchLast10(dbUrl, collectionName) {
var context = {
DB_URL: dbUrl,
DATA: {},
COLLECTION: collectionName
};
// cascade of all needed promises
return openDatabaseConnection(context)
.then(getData)
.then(closeDatabaseConnection);
}
function openDatabaseConnection(context) {
console.log('================================================');
console.log('opening database connection');
return MongoClient.connect(context.DB_URL)
.then(function (db, error) {
if (!error) {
console.log('DB connected');
//console.log(db);
context.DB = db;
return context;
} else {
console.log('Could not connect to database')
}
});
}
function getData(context) {
console.log('Getting data from database');
var collection = context.DB.collection(context.COLLECTION);
return collection.find().sort({date: -1}).limit(10).toArray().then(function (results, error) {
if (!error) {
console.log('Data retrieved');
context.DATA = results;
return context;
} else {
console.log('Could not retrieve data from database');
console.log(error);
closeDatabaseConnection();
}
});
}
function saveData(context) {
console.log('Saving data to database');
var collection = context.DB.collection(context.COLLECTION);
return collection.insertOne(context.DATA)
.then(function (results, error) {
if (!error) {
console.log('Data saved');
return context;
} else {
console.log('Could not save data to database');
console.log(error);
closeDatabaseConnection();
}
});
}
function closeDatabaseConnection(context) {
console.log('Closing database connection');
return context.DB.close(false)
.then(function (ok, error) {
if (!error) {
console.log('Database closed');
return context;
} else {
console.log('Could not close database connection');
}
});
}