moj*_*ker 6 javascript mongoose node.js express bluebird
我的朋友,不幸的是我找不到任何关于如何在节点js express mongoose app中实现bluebird promise库的例子.
我的应用程序设置为猫鼬模型,控制器和路由在不同的文件中.
但是用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);
}
});
};
Run Code Online (Sandbox Code Playgroud)
//猫鼬模型
/**
* 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);
Run Code Online (Sandbox Code Playgroud)
所以,如果我想使用Bluebird promise库,我将如何更改export.list
提前致谢.
一些问题,
我在哪里可以在猫鼬模型上调用promisify?例如Article = mongoose.model('Article');
like thisArticle = Promise.promisifyAll(require('Article')); 或者像这样
var Article = mongoose.model('Article');
Article = Promise.promisifyAll(Article);
Run Code Online (Sandbox Code Playgroud)
moj*_*ker 10
在互联网上搜索了好几周后,我能够在这里找到一个例子 为了在你的nodejs app中使用mongoose模型,
在定义了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.
Run Code Online (Sandbox Code Playgroud)
现在你可以像你一样在你的控制器中使用你的mongoose模型
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)
});
});
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5306 次 |
| 最近记录: |