首页 > 解决方案 > 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);????
    });
 });

标签: node.jsmongodbmongoosees6-promise

解决方案


您可以将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)

}

推荐阅读