mongoos nested query, await for second query to return the data

Viewed 128

I have a collection as following:

collection A:

 {
      _id: 5e8b1dd9e45da75adb2278fd,
      mobile: '445566',
      content_id: 5e8b1d1ae45da75adb2278fc,
      active: false,
    }

I have another collection like so:

collection B:

{
    title: {
      en: 'example title',
      xx: 'another title',
    },
    body: {
      en: 'example body',
      yy: 'another body',
    },
    _id: 5e8b1d1ae45da75adb2278fc,
  }

if you see the first collection contains the _id of the second collection, so I am using mongoose and each one I can list it separately and it is working fine, now I want to get all items in col A and since it is an array of items, I wanna do something like this:

async (req, res, err) {
  const allContents = [];
  const mobile = [];

  mobiles = await MyCollectionA.find({mobile: req.params.mobile})

  mobiles.forEach(async (mobile) => {
      const content = await MyCollectionB.findById(mobile.content_id);
      allContents.push(mobile, content);
      // if I do console.log(allContents), here I have all needed data available
  });
  console.log(allContents) // show me empty array, []
  res.json(allContents);
}

it seems it does not wait until the forEach finishes it job; I tried mongoose stream also couldn't achieve to what I want.

1 Answers

You could make it wait by using "for" loop or using Promise.all as I've shown below:

async (req, res, err) {
  const allContents = [];
  const mobile = [];

  mobiles = await MyCollectionA.find({mobile: req.params.mobile})

  await Promise.all( mobiles.map(async (mobile) => {
      const content = await MyCollectionB.findById(mobile.content_id);
      allContents.push(mobile, content);
  }));
  console.log(allContents) // show me empty array, []
  res.json(allContents);
}
Related