简体   繁体   中英

Node Js Async for loop and insert data in mongo

I have list of child collection Id's and running a for loop. In that for loop I try to find the parent collection data and insert in another collection. Sample code is given below

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

when I try to execute this code for loop gets completed before collection insert.So I need to insert collection on each iteration.

You could try doing it recursively if your test array isn't too long

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

You can try do it like that:

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

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

Insert can work directly with arrays

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM