I've been reading documentaion and articles and everyone seems to describe a different way about using Mongoose and Bluebird together. Even the official Mongoose documentation says something and Bluebird documentaion says another thing.
According to Mongoose:
mongoose.Promise = require('bluebird');
According to Bluebird:
var Promise = require("bluebird");
Promise.promisifyAll(require("mongoose"));
So to my understanding, if you pick the Mongoose way a sample query would be like:
User.findById('someId')
.then(function(){
// do stuff
})
.catch(function(err){
// handle error
})
But also in Mongoose docs it says that:
Mongoose queries are not promises. However, they do have a .then() function for yield and async/await. If you need a fully-fledged promise, use the .exec() function.
So in this case, is .then
above a promise or not?
If you go with Bluebird way:
User.findById('someId')
.execAsync()
.then(function(){
// do stuff
})
.catch(function(err){
// handle error
})
Or maybe even skip execAsync()
and start with findByIdAsync
instead.
Really confused with different documentaion. I'd appreciate if someone can shed some light into this.
Choose the Mongoose way:
mongoose.Promise = require('bluebird');
That's because Mongoose already supports promises (besides also accepting callbacks); the above code just replaces Mongoose's own promise library (mpromise
) by Bluebird (which is probably faster, better tested, and has more utility functions available).
Bluebird's promisify*()
is meant to allow code that doesn't already use promises (purely callback-based functions) to return promises.