0

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 });
        });

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

Josh
  • 2,430
  • 4
  • 18
  • 30

1 Answers1

1

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 });
    });
james emanon
  • 11,185
  • 11
  • 56
  • 97