Last active
June 10, 2020 08:58
-
-
Save taktran/7852034803c67b5eaa94263fbffa0916 to your computer and use it in GitHub Desktop.
Mongo db utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MongoClient = require('mongodb').MongoClient; | |
const assert = require('assert'); | |
exports.findInCollection = ({ db, collectionName }) => query => { | |
assert.notEqual(db, undefined); | |
const collection = db.collection(collectionName); | |
return collection.find(query).toArray(); | |
}; | |
exports.insertManyInCollection = ({ db, collectionName }) => (items = []) => { | |
assert.notEqual(db, undefined); | |
if (!items.length) { | |
return; | |
} | |
const collection = db.collection(collectionName); | |
return collection.insertMany(items).then(result => { | |
const { insertedCount, insertedIds } = result; | |
return { insertedCount, insertedIds }; | |
}); | |
}; | |
exports.deleteManyInCollection = ({ db, collectionName }) => query => { | |
assert.notEqual(db, undefined); | |
const collection = db.collection(collectionName); | |
return collection.deleteMany(query).then(result => { | |
const { deletedCount } = result; | |
return { deletedCount }; | |
}); | |
}; | |
exports.connectToMongo = ({ mongoUrl, options = {} }) => { | |
return MongoClient.connect(mongoUrl, options).then(client => { | |
const db = client.db(); // Use db from mongoUrl | |
const dbCleanup = () => client.close(); | |
return { db, dbCleanup }; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment