等待猫鼬解析数据,然后再返回 [英] Wait for Mongoose to resolve data before returning

查看:48
本文介绍了等待猫鼬解析数据,然后再返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历此数组并将用户对象附加到其中的每个对象.在将JSON返回给客户端之前,如何等待它们完成?

I'm trying to loop through this array and append user objects to each object inside. How do I wait for each of them to complete before returning the JSON to the client?

       Match.find()
        .or([{ user_id: req.user._id }, { second_user_id: req.user._id }])
        .exec((err, result) => {
            if (err) {
                return res.sendStatus(500);
            }

            result.map(async match => {
                match.user = await User.findById(req.user._id).exec();
            });

            return res.json({ matches: result });
        });

在这种情况下,在Mongoose有机会解决findById查询之前,将数组返回给客户端.

In this case the array is returned to the client before Mongoose has a chance to resolve the findById queries.

推荐答案

尝试一下,让我知道它的运行方式:

Try this and let me know how it goes:

  Match.find()
    .or([{ user_id: req.user._id }, { second_user_id: req.user._id }])
    .exec(async(err, result) => {
        if (err) {
            return res.sendStatus(500);
        }

        const results = await Promise.all(result.map(async match => {
            match.user = await User.findById(req.user._id).exec();
        }));

        return res.json({ matches: results });
    });

这篇关于等待猫鼬解析数据,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆