Search code examples
javascriptnode.jsmongodbnode-mongodb-native

How to add result of a mongo find query into another find query


First of all I am searching for all group documents in my collection:

const groups = await Content.find({ type: 'group' }).toArray()

For this array I need to find each children documents and add them to the object:

groups.map(async g => {
  g.content = await Content.find({
    type: 'element',
    parent: g._id
  }).toArray()

  console.log(g) // <-- has content field, which is what I am expecting
})

console.log(groups) // <-- content field is missing

Example

To make it a bit more clearer: groups could have this result:

[{
  _id: 'xxnQt5X8pfbcJMn6i',
  title: 'Title',
  type: 'group',
}]

Now I'm searching for each element (in this example it has only one) for all documents with the parent ID and this result should be added as a field to group.

[{
  _id: 'xxnQt5X8pfbcJMn6i',
  title: 'Title',
  type: 'group',
  content: [
    { _id: '1', title: 'example', parent: 'xxnQt5X8pfbcJMn6i' },
    { _id: '2', title: 'another example', parent: 'xxnQt5X8pfbcJMn6i' }
  ]
}]

In my attempt I do not get the content when doing console.log outside the map().

And maybe it is possible to do this directly with my mongoDB query (I'm using mongoDB native driver)


Solution

  • This is the perfect case where you are looking for Promise.all

    var promiseArray = groups.map(g => {
      return Content.find({type: 'element',parent: g._id},function(err,cursor){
           g['content'] = cursor.toArray();
           return g;
      });
    })
    
    Promise.all(promiseArray ).then(function(groups) {
        console.log(groups)
    })