Reputation: 137
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?
Upvotes: 1
Views: 444
Reputation: 707218
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.
Upvotes: 2
Reputation: 2154
The error you obtained was caused by defining mongoose.Promise
rather than Promise
, and then using Promise
, a variable that doesn't exist in that scope.
The second approach doesn't seem to be modifying anything within mongoose
whatsoever. However just to be sure it would be interesting to see how promiseArray
is defined.
Then, I do not recommend passing undefined
as handlers for then
and catch
.
Upvotes: 0