javascript - 使用 nodejs 、 express 和 mongoose 的 bluebird Promisies crud 示例

标签 javascript node.js express mongoose bluebird

我的 friend 们,不幸的是我找不到任何关于如何在 node js express mongoose 应用程序中实现 bluebird promise 库的示例。

我的应用程序设置中 Mongoose 模型、 Controller 和路由位于不同的文件中。

但是用 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);
      }
  });
};

// Mongoose 模型

 /**
 * 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

提前致谢。

一些问题,

在 mongoose 模型上我在哪里调用 promisify? 例如 Article = mongoose.model('Article'); 像这样Article = Promise.promisifyAll(require('Article')); 要么 像这样

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

最佳答案

好的,在互联网上搜索了数周后,我找到了一个示例 here 为了在您的 nodejs 应用程序中使用 Mongoose 模型,

您需要像这样 promise 库和模型实例 在你的模型模块中,在你定义了你的模式之后

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

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

现在你可以像这样在你的 Controller 中使用你的 Mongoose 模型作为一个 promise

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

关于javascript - 使用 nodejs 、 express 和 mongoose 的 bluebird Promisies crud 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25555139/

相关文章:

javascript - 圆形对象内的图像导致像素化 d3 js

javascript - 两个网站的 Ghost 管理员

node.js - Express.js 中的 CookieParser 和 CookieSession 中间件

node.js - Express Validator 的值无效

javascript - 滚动时背景图像变化

javascript - 随着鼠标指针位置的改变而改变文本?

javascript - 使用 JavaScript 在空闲时隐藏鼠标光标

node.js - 状态错误 : Insecure HTTP is not allowed by platform:

node.js - MongoDB 查找和展开未给出正确结果

javascript - 在 Jade View 上获取 'Syntax Error'