Mongoose with promise

Q) How to configure so that mongoose library uses promises instead of callback?
a) Firstly, mongoose library is "imported" using the require('mongoose') statement;
var mongoose = require('mongoose');
b) mongoose library has a property that can be assigned with the promise library to be used.
c) bluebird is a promise library.
d) Import bluebird into your app.
var bluebird = require('bluebird');
e) Assign bluebird as the promise library for mongoose.
mongoose.promise = bluebird;
f)  mongoose.connect is the method that mongoose library uses to connect to a particular mongodb instance.
mongoose.connect(config.mongoConnStr, {
    promiseLibrary: bluebird
}, function (err) {
    if (err) throw err;
    console.log('Successfully connected to MongoDB using: ' + config.mongoConnStr);
});
g) This mongoose.connect method takes three parameters.
1) The connection string
2) A config object which can take various configuration properties
3) An error callback function which mongoose would invoke in the event of an error while doing the connect action.

h) The config object, the second parameter to the connect method can take an attribute named 'promiseLibrary'
i) To have mongoose connect through promises, this key needs to be set to a promise library.
j) Here, we have bluebird as the imported promise library. Set that on the config object as
   {
     promiseLibrary: bluebird
   }
k) The connect call nows looks as follows
mongoose.connect(config.mongoConnStr, {
    promiseLibrary: bluebird
}, function (err) {
    if (err) throw err;
    console.log('Successfully connected to MongoDB using: ' + config.mongoConnStr);
});


Comments

Popular posts from this blog

MongoDB