Skip to content

Instantly share code, notes, and snippets.

@mdnmdn
Created August 14, 2019 22:03
Show Gist options
  • Save mdnmdn/98fd1a4c20ae8f8ae76d9c7f72b12851 to your computer and use it in GitHub Desktop.
Save mdnmdn/98fd1a4c20ae8f8ae76d9c7f72b12851 to your computer and use it in GitHub Desktop.
Node mongo connection with promises
// npm i mongodb
const { MongoClient } = require('mongodb');
const MONGODB_URI = 'mongodb://localhost:27021/testdata';
let mongoConnection = null;
const getMongo = async () => {
if (!mongoConnection){
mongoConnection = await MongoClient.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
}
return mongoConnection;
}
const getMongoDb = async (name = null) => {
const mongo = await getMongo();
return mongo.db(name);
}
const doSomething = async () => {
const db = await getMongoDb();
await db.collection('things').insertOne({d:1});
const rowCount = await db.collection('things').countDocuments();
console.log({ rowCount });
}
exports.getMongo = getMongo;
exports.getMongoDb = getMongoDb;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment