javascript - 将 Bluebird Promisifyall 与 Mongoose 结合使用

标签 javascript mongodb mongoose promise bluebird

我将 mongoose 与 Bluebird promisifyall 一起使用,如下所示:

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

我想使用以下方式从 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
      });
    });
};

但它只是挂起,我做错了什么吗? 如果您能在使用 bluebird 的 promisifyall 和 mongoose 方面获得任何帮助,我将不胜感激,谢谢:)

最佳答案

findwhere 不是异步的,它们不接受回调。因此,不要使用它们的 ...Async 变体 - 您不希望它们返回 promise ,您需要一个 mongoose 查询对象。

尝试

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

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

关于javascript - 将 Bluebird Promisifyall 与 Mongoose 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446373/

相关文章:

javascript - 水平自动收报机被过早切断?

mongodb - 从子文档数组中删除数组元素

node.js - Mongoose 虚拟机是否困惑?

mongoose - findOneAndUpdate 方法在解析前返回

javascript - 如何在没有滚动条(实际滚动)的情况下增加滚动上的数字?

javascript - 如何在 Ionic/Angular 中访问 json 对象

java - 使用 Java 在 MongoDB 中创建数据库用户

node.js - 无法从 mongodb-atlas 获取数据?

javascript - 在 FORM 的选择中使用图像的最佳实践

mongodb - 对书籍进行分组并计算每个书籍的评分