Skip to content

Instantly share code, notes, and snippets.

@taktran
Last active June 10, 2020 08:58
Show Gist options
  • Save taktran/7852034803c67b5eaa94263fbffa0916 to your computer and use it in GitHub Desktop.
Save taktran/7852034803c67b5eaa94263fbffa0916 to your computer and use it in GitHub Desktop.
Mongo db utils
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