bluebird Promisies crud example using nodejs , express and mongoose bluebird Promisies crud example using nodejs , express and mongoose express express

bluebird Promisies crud example using nodejs , express and mongoose


Ok after scouring around the internet for weeks, i was able to find an example hereIn order to work with mongoose models in your nodejs app,

You need to promisify the Library and the model Instance like soin your model module, after you have defined your Schema

var Article = mongoose.model('Article', ArticleSchema);Promise.promisifyAll(Article);Promise.promisifyAll(Article.prototype);exports.Article = Article;//Replace Article with the name of your Model.

Now you can use your mongoose model as a promise in your controller like this

exports.create = function(req, res) {    var article = new Article(req.body);    article.user = req.user;    article.saveAsync().then(function(){        res.jsonp(article);    }).catch(function (e){        return res.status(400).send({            message: errorHandler.getErrorMessage(e)        });    });  };


You actually can do an even simpler one-liner at the top of your Model.

var mongoose = require('bluebird').promisifyAll(require('mongoose'));

Create your model like normal, and voila. Everything is promisified for you.


Even tough the question is already answered. I think a better way to promisify mongoose is to do the following:

Promise.promisifyAll(mongoose.Model);Promise.promisifyAll(mongoose.Model.prototype);Promise.promisifyAll(mongoose.Query.prototype);

This way all modules automatically have the Async functions.

See also: mongoose-bird for a library doing exactly this.