How to use MongoDB with promises in Node.js?
You can also do async/await
async function main(){
let client, db;
try{
client = await MongoClient.connect(mongoUrl, {useNewUrlParser: true});
db = client.db(dbName);
let dCollection = db.collection('collectionName');
let result = await dCollection.find();
// let result = await dCollection.countDocuments();
// your other codes ....
return result.toArray();
}
catch(err){ console.error(err); } // catch any mongo error here
finally{ client.close(); } // make sure to close your connection after
}
Your approach is almost correct, just a tiny mistake in your argument
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/example'
MongoClient.connect(url)
.then(function (db) { // <- db as first argument
console.log(db)
})
.catch(function (err) {})