Node Js Async for循环并在mongo中插入数据

时间:2017-10-21 10:13:47

标签: javascript node.js mongodb collections

我有子集合ID列表并运行for循环。在for循环中,我尝试查找父集合数据并插入另一个集合中。示例代码如下所示

for(let i=0; i<test.length; i++;){
 db.collection('Parent').find({ "Id" : test[i].Id }).toArray(function(err, result){
  if(result.length > 0){
    db.collection('anotherCollection', function(err, collection){
      collection.insert({
        field1: test[i].field1,
        field2: test[i].field2
      })
    })
  }
})
}

当我尝试执行此代码时,循环在集合插入之前完成。所以我需要在每次迭代时插入集合。

2 个答案:

答案 0 :(得分:0)

如果你的测试数组不是太长,你可以尝试递归地执行它

function doAsyncLoop(i, test) {
    if (i < test.length) {
        db.collection('Parent').find({
            "Id": test[i].Id
        }).toArray(function(err, result) {
            if (result.length > 0) {
                db.collection('anotherCollection', function(err, collection) {
                    collection.insert({
                        field1: test[i].field1,
                        field2: test[i].field2
                    });
                    doAsyncLoop(i++, test);
                })
            } else {
                 doAsyncLoop(i++, test);
            }
        })
    }
}

答案 1 :(得分:0)

您可以尝试这样做:

const data = db.collection('Parent').find({ "Id" : test[i].Id }).toArray();

db.collection('anotherCollection').insert(data);

Insert可以直接使用数组

相关问题