繁体   English   中英

bluebird Promisies crud示例使用nodejs,express和mongoose

[英]bluebird Promisies crud example using nodejs , express and mongoose

我的朋友,不幸的是我找不到任何关于如何在节点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,
        default: '',
        trim: true
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

mongoose.model('Article', ArticleSchema);

所以,如果我想使用Bluebird promise库,我将如何更改export.list

提前致谢。

一些问题,

我在哪里可以在猫鼬模型上调用promisify? 例如Article = mongoose.model('Article'); like this Article = mongoose.model('Article'); like this文章= Promise.promisifyAll(require('Article')); 或者像这样

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

在互联网上搜索了好几周后,我能够在这里找到一个例子为了在你的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.

现在你可以像你一样在你的控制器中使用你的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)
        });
    });
  };

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

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

像平常一样创建你的模型,瞧。 一切都为你承诺。

即使是艰难的问题也已得到解决。 我认为宣传猫鼬的更好方法是做以下事情:

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

这样,所有模块都自动具有异步功能。

另请参阅: mongoose-bird用于完成此操作的库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM