db.js 1.5 KB
// 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
};