I am currently working with Mongoose and Bluebird as a plugged in Promise library. Following mongoose docs, I have done the following:
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
// Some function making use of Bluebird's Promise.map()
function someFn() {
return Promise.map([
someModel.findById(someId).exec(),
someOtherModel.findById(someOtherId).exec()
], mapperFn)
.then(function() {})
.catch(function() {});
}
As you can see, I am trying to use bluebird's Promise.map()
in my code, but I keep getting the following error:
TypeError: Promise.map is not a function
Then I tried by requiring bluebird and setting it to a new var Promise
, like this
var mongoose = require('mongoose');
var Promise = require('bluebird');
// Some function making use of Bluebird's Promise.map()
function someFn() {
return Promise.map([
someMode.findById(someId).exec(),
someOtherModel.findById(someOtherId).exec()
], mapperFn)
.then(function() {})
.catch(function() {});
}
This worked, but does not seem to be the right way to approach this issue. I do not know if this might cause any conflicts with other variables in the mongoose code.
Any suggestions to make this work?
In order to use Promise.map()
, you need to define Promise
to be Bluebird's object, not just the regular ES6 Promise
. You would do that like this:
let Promise = require('bluebird');
mongoose.Promise = Promise;
Or, you could even just do this:
let Promise = mongoose.Promise = require('bluebird');
As it was, you were trying to do Promise.map()
with the regular ES6 version of Promise
.
Your second approach was properly defining Promise
to be Bluebird's library and that's why Promise.map()
worked, but you were not using Bluebird's promises with mongoose which will work in some cases because of promise interoperability between different types of promises as long as you only use .then()
on the promises that come back from mongoose and nothing special like the myriad of Bluebird additional methods.