2014-08-28 63 views
6

我的朋友们,不幸的是,我找不到任何有关如何在节点js express mongoose应用程序中实现蓝鸟许诺库的例子。bluebird promisies使用nodejs,express和mongoose的crud示例

我的应用程序安装在mongoose模型,控制器和路由在不同文件中。

但实施它与猫鼬,我只是不知道。

所以请有人可以告诉我它是如何使用的。请看下面。

//express controller Article.js 


var mongoose = require('mongoose'), 
errorHandler = require('./errors'), 
Article = mongoose.model('Article'); 

exports.list = function(req, res) { 
Article.find().sort('-created').populate('user', 'displayName').exec(function(err, articles) { 
     if (err) { 
      return res.status(400).send({ 
      message: errorHandler.getErrorMessage(err) 
      }); 
     } else { 
      res.jsonp(articles); 
     } 
    }); 
}; 

//猫鼬型号

/** 
* Module dependencies. 
*/ 
var mongoose = require('mongoose'), 
Schema = mongoose.Schema; 

/** 
* Article Schema 
*/ 
var ArticleSchema = new Schema({ 
    created: { 
     type: Date, 
     default: Date.now 
    }, 
    title: { 
     type: String, 
     default: '', 
     trim: true, 
     required: 'Title cannot be blank' 
    }, 
    content: { 
     type: String, 
     default: '', 
     trim: true 
    }, 
    user: { 
     type: Schema.ObjectId, 
     ref: 'User' 
    } 
}); 

mongoose.model('Article', ArticleSchema); 

所以,请,如果我想使用蓝鸟承诺库,我将如何去事先改变export.list

感谢。

一些问题,

我在哪里可以打电话promisify上的猫鼬模型? 例如Article = mongoose.model('Article'); like this Article = Promise.promisifyAll(require('Article')); 或 这样

var Article = mongoose.model('Article'); 
    Article = Promise.promisifyAll(Article); 

回答

10

好周围的互联网数周精练后,我能找到一个例子here 为了在你的NodeJS应用与猫鼬模型工作,

您需要promisify图书馆和像这样 模型模块,模型实例之后,您已经定义模式现在

var Article = mongoose.model('Article', ArticleSchema); 
Promise.promisifyAll(Article); 
Promise.promisifyAll(Article.prototype); 

exports.Article = Article; 
//Replace Article with the name of your Model. 

你可以使用你米ongoose模型作为你的控制器的承诺,像这样

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) 
     }); 
    }); 
    }; 
1

即使这个问题已经很难回答了。我认为更好的方式来promisify猫鼬是做到以下几点:

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

这样,所有的模块将自动拥有异步功能。

另请参阅:mongoose-bird一个图书馆正在做这件事。

2

您实际上可以在模型的顶部做一个更简单的单线程。

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

创建你的模型像正常,瞧。一切都为你而设。

+0

你知道如何用es6做到这一点吗? 我怎么会promination这个'从mongoose'进口猫鼬';' – 2016-06-01 05:19:01

+0

我相信它会是这样的:'从'mongoose'进口{mongoose}; 从'bluebird'导入{bluebird}; var mongoose = bluebird.promisifyAll(mongoose);'但我不确定。你可以混合commonJS与es6两种方式,所以我不会担心它@JesusAdolfoRodriguez – 2016-06-01 14:59:25