How to use mongoose Promise - mongo
Can someone give me an example on how to use a Promise with mongoose. Here is what I have, but its not working as expected:
app.use(function (req, res, next) {
res.local('myStuff', myLib.process(req.path, something));
console.log(res.local('myStuff'));
next();
});
and then in myLib, I would have something like this:
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
promise.resolve.bind(promise)(err, docs);
});
return promise;
};
At some point I am expecting my data to be present, but how can I access it, or get at it?
In the current version of Mongoose, the exec()
method returns a Promise, so you can do the following:
exports.process = function(r) {
return Content.find({route: r}).exec();
}
Then, when you would like to get the data, you should make it async:
app.use(function(req, res, next) {
res.local('myStuff', myLib.process(req.path));
res.local('myStuff')
.then(function(doc) { // <- this is the Promise interface.
console.log(doc);
next();
}, function(err) {
// handle error here.
});
});
For more information about promises, there's a wonderful article that I recently read: http://spion.github.io/posts/why-i-am-switching-to-promises.html
Mongoose already uses promises, when you call exec()
on a query.
var promise = Content.find( {route : r }).exec();
Mongoose 4.0 Release Notes
Mongoose 4.0 brings some exciting new functionality: schema validation in the browser, query middleware, validation on update, and promises for async operations.
With [email protected] you can use any promises that you want
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
Another example with polyfilling global.Promise
require('es6-promise').polyfill();
var mongoose = require('mongoose');
So, you can just do later
Content
.find({route : r})
.then(function(docs) {}, function(err) {});
Or
Content
.find({route : r})
.then(function(docs) {})
.catch(function(err) {});
P.S. Mongoose 5.0
Mongoose 5.0 will use native promises by default if available, otherwise no promises. You will still be able to set a custom promises library using
mongoose.Promise = require('bluebird');
, however, mpromise will not be supported.
I believe you're looking for
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
if(err) {
promise.error(err);
return;
}
promise.complete(docs);
});
return promise;
};