【问题标题】:Using Bluebird Promisifyall with Mongoose将 Bluebird Promisifyall 与 Mongoose 一起使用
【发布时间】:2015-12-03 11:08:30
【问题描述】:

我正在使用带有 Bluebird promisifyall 的猫鼬,如下所示:

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

我想使用 where 从 mongo 中检索文档,如下所示:

// Gets a list of Posts
exports.index = function(req, res) {
  console.log(req.query);
  Post.findAsync()
    .whereAsync({author: req.query.id})
    .execAsync()
    .then(function(entity) {
            if (entity) {
              res.status(statusCode).json({
                status_code: statusCode,
                data: entity
              });
            }
    })
    .catch(function(err) {
      res.status(200).json({
        status_code: statusCode,
        message: 'error occured',
        errors: err
      });
    });
};

但它只是挂起,我做错了什么? 将不胜感激使用蓝鸟和猫鼬的 promisifyall 的任何帮助,谢谢:)

【问题讨论】:

  • Mongoose 已经原生地返回了一个 Promise,而不需要拉入 bluebird Promise。如前所述,唯一获得“承诺”的方法是异步方法,如 .findOne().findOneAsync(),而不是非异步的“助手”,如 .where()。简而言之,除非您特别想要“添加”,例如 .spread(),否则您不需要 bluebird 承诺

标签: javascript mongodb mongoose promise bluebird


【解决方案1】:

findwhere 不是异步的,它们不接受回调。所以不要使用它们的…Async 变体——你不希望它们返回一个承诺,你想要一个猫鼬查询对象。

试试

Post.find().where({author: req.query.id}).execAsync()
.then(…)
.…

顺便说一句,如果entity 是虚假的,您的请求确实会挂起,在这种情况下您永远不会写响应。考虑添加elsethrow new Error("no entity")

【讨论】:

  • 谢谢,这解决了。我有处理未找到实体和其他类似的功能,只是没有在这里包含它
猜你喜欢
  • 2015-09-11
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 2019-04-15
  • 1970-01-01
  • 2020-01-17
相关资源
最近更新 更多