2017-10-21 102 views
0

我有一个子集合Id的列表并运行for循环。在该循环中,我尝试查找父集合数据并插入另一个集合中。示例代码如下节点Js Async for循环并在mongo中插入数据

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

当我尝试执行此代码的循环在集合之前完成insert.So我需要在每次迭代中插入集合。

+0

我曾使用“async.eachSeries”并解决了这个问题。 –

回答

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

你可以尝试那样做:

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

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

插入可以直接阵列工作