I am trying to use Bluebird with mongoose. Here is my implementation.
const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const Entity = require('./entity');
mongoose.Promise = Bluebird;
Now I try to do something like this.
let promises = [];
promises.push(Entity.findOne({ country: 'HONGKONG' }));
promises.push(Entity.findOne({ country: 'INDIA' }));
promises.push(Entity.findOne({ country: 'THAILAND' }));
I know the above query doesn't make sense. It's just an example for multiple promise.
Now I try to implement Bluebirds reflect
return Bluebird.all(promises.map(function (promise) {
return promise.reflect();
}))
.then(response => {
console.log(response.filter(r => r.isFulfilled() ));
console.log(response.filter(r => !r.isFulfilled() ));
}).catch(err=>{
console.log(err);
})
I get error promise.reflect is not a function
But, When I do this, It works fine.
promises.push(new Bluebird( (resolve, reject) => resolve(Entity.findOne({ country: 'HONGKONG' } )) ));
promises.push(new Bluebird( (resolve, reject) => resolve(Entity.findOne({ country: 'INDIA' } )) ));
promises.push(new Bluebird( (resolve, reject) => resolve(Entity.findOne({ country: 'THAILAND' } )) ));
My question is, Why mongoose is not taking bluebird's promise implementation normally. Do I need to explicitly resolve each query with Bluebird?
I think it fails because .findOne() does not return a Promise, but a Query Object. You have to add .exec() at the end.
Try:
let promises = [];
promises.push(Entity.findOne({ country: 'HONGKONG' }).exec());
promises.push(Entity.findOne({ country: 'INDIA' }).exec());
promises.push(Entity.findOne({ country: 'THAILAND' }).exec());
Here you have more information about Promises in Mongoose. Why you need to use the .exec()
function is explained as well.