Created
August 14, 2019 22:03
-
-
Save mdnmdn/98fd1a4c20ae8f8ae76d9c7f72b12851 to your computer and use it in GitHub Desktop.
Node mongo connection with promises
This file contains 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
// 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