What is the correct way of using Bluebird for Mongoose promises?
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.
From Bluebird doc
Promise.promisifyAll( Object target, [Object { suffix: String="Async", multiArgs: boolean=false, filter: boolean function(String name, function func, Object target, boolean passesDefaultFilter), promisifier: function(function originalFunction, function defaultPromisifier) } options] ) -> Object
as you can see, by default, promisifyAll add suffix 'Asyns', so if you are using this way of promisification:
var Promise = require("bluebird");Promise.promisifyAll(require("mongoose"));
the async version of User.findById
will be User.findByIdAsync
what about mongoose.Promise
then you use promise library like
mongoose.Promise = require('bluebird');
built-in promise mechanism replaced by library: query.exec().constructor
replaced by require('bluebird')
so instead .exec()
for return promise, you can use bluebird probabilities directly for mongoose queries like
User.findOne({}).then(function(user){ // ..})
For those of you using TypeScript, the correct way is:
(<any>mongoose).Promise = YOUR_PROMISE;
From the documentation:
Typescript does not allow assigning properties of imported modules. To avoid compile errors use one of the options below in your code:(<any>mongoose).Promise = YOUR_PROMISE;require('mongoose').Promise = YOUR_PROMISE;import mongoose = require('mongoose'); mongoose.Promise = YOUR_PROMISE;