-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
46 lines (39 loc) · 1.03 KB
/
db.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
// Handle to wait for db connection
var mongo = require('mongodb');
const databaseName = 'sugarizerDb';
//- Utility functions
// Init database
exports.waitConnection = function(callback) {
var waitTime = 5;
if (waitTime) {
var timer = setInterval(function() {
var client = createConnection();
// Open the db
client.connect(function(err, client) {
if (!err) {
clearInterval(timer);
var db = client.db(databaseName);
callback(db);
} else {
console.log("Waiting for DB... ("+err.name+")");
}
});
}, waitTime*1000);
} else {
var client = createConnection();
// Open the db
client.connect(function(err, client) {
if (!err) {
var db = client.db(databaseName);
callback(db);
} else {
callback();
}
});
}
};
function createConnection() {
return new mongo.MongoClient(
(process.env.MONGO_URL || 'mongodb://localhost:27017')+'/'+ databaseName,
{auto_reconnect: false, w:1, useNewUrlParser: true, useUnifiedTopology: true });
}