How to use mongoose Promise - mongo
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 4.0 brings some exciting new functionality: schema validation in the browser, query middleware, validation on update, and promises for async operations.
With mongoose@4.1 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.