如何将mongo查找查询的结果添加到另一个查找查询中

时间:2018-05-17 17:02:21

标签: javascript node.js mongodb node-mongodb-native

首先,我正在搜索我的收藏中的所有小组文件:

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

对于这个数组,我需要找到每个子文档并将它们添加到对象中:

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

实施例

为了使它更清晰:groups可能会产生这样的结果:

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

现在我正在搜索具有父ID的所有文档的每个元素(在此示例中只有一个元素),此结果应作为字段添加到group

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

在我的尝试中,当在map()之外执行console.log时,我没有得到内容。

也许可以直接使用我的mongoDB查询(我使用mongoDB native driver

1 个答案:

答案 0 :(得分:0)

这是您寻找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)
})