我将 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 方面获得任何帮助,我将不胜感激,谢谢:)
最佳答案
find
和 where
不是异步的,它们不接受回调。因此,不要使用它们的 ...Async
变体 - 您不希望它们返回 promise ,您需要一个 mongoose 查询对象。
尝试
Post.find().where({author: req.query.id}).execAsync()
.then(…)
.…
顺便说一句,如果 entity
为假,您的请求就会挂起,在这种情况下您永远不会编写响应。考虑添加一个 else
和 throw new Error("no entity")
。
关于javascript - 将 Bluebird Promisifyall 与 Mongoose 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446373/