How to use MongoDB with promises in Node.js?
I've been trying to discover how to use MongoDB with Node.js and in the docs it seems the suggested way is to use callbacks. Now, I know that it is just a matter of preference, but I really prefer using promises.
The problem is that I didn't find how to use them with MongoDB. Indeed, I've tried the following:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/example';
MongoClient.connect(url).then(function (err, db) {
console.log(db);
});
And the result is undefined
. In that case it seems this is not the way to do so.
Is there any way to use mongo db inside Node with promises instead of callbacks?
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) {})
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
}
Since none of the answers above mention how to do this without bluebird or q or any other fancy library, let me add my 2 cents on this.
Here's how you do an insert with native ES6 promises
'use strict';
const
constants = require('../core/constants'),
mongoClient = require('mongodb').MongoClient;
function open(){
// Connection URL. This is where your mongodb server is running.
let url = constants.MONGODB_URI;
return new Promise((resolve, reject)=>{
// Use connect method to connect to the Server
mongoClient.connect(url, (err, db) => {
if (err) {
reject(err);
} else {
resolve(db);
}
});
});
}
function close(db){
//Close connection
if(db){
db.close();
}
}
let db = {
open : open,
close: close
}
module.exports = db;
I defined my open() method as the one returning a promise. To perform an insert, here is my code snippet below
function insert(object){
let database = null;
zenodb.open()
.then((db)=>{
database = db;
return db.collection('users')
})
.then((users)=>{
return users.insert(object)
})
.then((result)=>{
console.log(result);
database.close();
})
.catch((err)=>{
console.error(err)
})
}
insert({name: 'Gary Oblanka', age: 22});
Hope that helps. If you have any suggestions to make this better, do let me know as I am willing to improve myself :)
This is a General answer for How to use MongoDB with promises in Node.js?
mongodb will return a promise if the callback parameter is omitted
Before converting to Promise
var MongoClient = require('mongodb').MongoClient,
dbUrl = 'mongodb://db1.example.net:27017';
MongoClient.connect(dbUrl,function (err, db) {
if (err) throw err
else{
db.collection("users").findOne({},function(err, data) {
console.log(data)
});
}
})
After converting to Promise
//converted
MongoClient.connect(dbUrl).then(function (db) {
//converted
db.collection("users").findOne({}).then(function(data) {
console.log(data)
}).catch(function (err) {//failure callback
console.log(err)
});
}).catch(function (err) {})
Incase you need to handle multiple request
MongoClient.connect(dbUrl).then(function (db) {
/*---------------------------------------------------------------*/
var allDbRequest = [];
allDbRequest.push(db.collection("users").findOne({}));
allDbRequest.push(db.collection("location").findOne({}));
Promise.all(allDbRequest).then(function (results) {
console.log(results);//result will be array which contains each promise response
}).catch(function (err) {
console.log(err)//failure callback(if any one request got rejected)
});
/*---------------------------------------------------------------*/
}).catch(function (err) {})