我的朋友,不幸的是我找不到任何关于如何在节点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);
- }
- });
- };
//猫鼬模型
- /**
- * 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,trim: true
- },user: {
- type: Schema.ObjectId,ref: 'User'
- }
- });
- mongoose.model('Article',ArticleSchema);
所以,如果我想使用Bluebird promise库,我将如何更改export.list
提前致谢.
一些问题,
我在哪里可以在猫鼬模型上调用promisify?
例如Article = mongoose.model(‘Article’);
喜欢thisArticle = Promise.promisifyAll(require(‘Article’));
要么
像这样
- var Article = mongoose.model('Article');
- Article = Promise.promisifyAll(Article);
解决方法
好几个星期在互联网上搜索后,我找到了一个例子
here
为了在nodejs app中使用mongoose模型,
为了在nodejs app中使用mongoose模型,
你需要像这样宣传图书馆和模型实例
在定义架构后,在模型模块中
- var Article = mongoose.model('Article',ArticleSchema);
- Promise.promisifyAll(Article);
- Promise.promisifyAll(Article.prototype);
- exports.Article = Article;
- //Replace Article with the name of your Model.
现在你可以像你一样在你的控制器中使用你的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)
- });
- });
- };