2017-10-21 105 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); 

插入可以直接陣列工作