UNPKG

gigaaa-chatbot-auth-extended

Version:
57 lines (49 loc) 1.67 kB
const MongoClient = require('mongodb').MongoClient; var ObjectId = require('mongodb').ObjectId module.exports = { initDb: initDb, getEntityById: getEntityById, getEntityByMongoQuery: getEntityByMongoQuery, updateEntity: updateEntity, insertNewEntity: insertNewEntity } // DB instance var db = null; async function initDb(url, dbName) { return MongoClient.connect(url, { useNewUrlParser: true }) .then((client) => { console.log("Connected successfully to server"); db = client.db(dbName); }); } async function getEntityById(id) { const collection = db.collection(entityName); return collection.find({ "_id": ObjectId(id) }).toArray() .then((usersCollection) => { if (usersCollection.length > 0) { return usersCollection[0]; } return null; }); } async function getEntityByMongoQuery(query, entityName) { const collection = db.collection(entityName); return collection.find(query).toArray() .then((foundDocuments) => { return foundDocuments; }); } async function updateEntity(entityId, enitityData, entityName) { const collection = db.collection(entityName); return collection.replaceOne({ "_id": ObjectId(entityId) }, enitityData) .then((res) => { return enitityData; }); } async function insertNewEntity(enitityData, entityName) { const collection = db.collection(entityName); return collection.insertOne(enitityData) .then((res) => { return enitityData; }) }