db.js
1.5 KB
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
// MongoDB handling module
// TODO: error handling, data removal
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
var db, collection;
// Use connect method to connect to the server
const init = function () {
MongoClient.connect(url, function (err, client) {
if (err) {
return;
}
console.log("Connected successfully to MongoDB server");
db = client.db('telegrambot');
collection = db.collection('users');
});
}
const findData = function (userId, key, callback) {
collection.find({ "userId": userId }).toArray(function (err, docs) {
var cur = docs[0];
if (cur != undefined) {
const keys = key.split('.');
for (var i = 0, subKey, len = keys.length; i < len; ++i) {
subKey = keys[i];
if (subKey == '') {
continue;
}
if (cur.hasOwnProperty(subKey)) {
cur = cur[subKey];
} else {
cur = undefined;
break;
}
}
}
callback(cur);
});
};
const updateData = function (userId, data, callback) {
collection.updateOne(
{ "userId": userId },
{ $set: data },
{ upsert: true },
function (err, result) {
callback(result);
});
};
module.exports = {
init: init,
findPref: findData,
updatePref: updateData
};