node.js - Mongoose:forEach 中的 Multi find() - 最终的 then() 在哪里
问题描述
我使用 multi find() 来填充 'categories' 和 'pic' 的 'post'。但是我不知道最终完整返回到'res.send(posts)'的数据在哪里。或者使用另一种方法,例如'Promise.all',请帮我解决问题
Post.find().then(posts=> {
async.forEach(posts, function(post, done) {
Cat.find().where('posts').in([post.id]).then(categories=> {
post.categories = categories;
var id=mongoose.Types.ObjectId(post.id);
File.findOne({'related.ref': id}).then(pic=>{
post.pic=pic;
});
})
//res.send(posts);????
});
});
解决方案
您可以将async-await用于您的路由处理程序:
async (req, res) => {
const posts = await Post.find()
for (post of posts) {
const categories = await Cat.find().where('posts').in([ post.id ])
post.categories = categories
const id = mongoose.Types.ObjectId(post.id)
const pic = await File.findOne({ 'related.ref': id })
post.pic = pic
}
res.send(posts)
}
推荐阅读
- javascript - JavaScript 链接导致随机 url
- prolog - 遍历数字的递归函数不进行
- swift - deinit 没有被调用。帮我解决这个问题
- syntax - PROLOG 中的垂直斜线函数到底是什么?是运营商吗?
- python - Selenium Chrome 驱动程序 Python 无头模式“拒绝访问”页面
- windows - 链接组装
- apache - ModSecurity 统计一个 IP 访问的主机数量
- python - 无法从 python 中的“flask.helpers”导入名称“_endpoint_from_view_func”
- visual-studio - 如何在 Visual Studio for Mac 中将 Apple 类添加到项目中
- javascript - TypeError:使用机车滚动反应模块时无法读取 null 的属性“offsetHeight”