0

I need to call some function after finishing callback execution using Node.js and MongoDB. I am providing my code below.

var updateArr=[];
TempCollection.find({},function(err,docs){
    for(var i=0;i<docs.length;i++){
        if (docs[i]['login_id']=='' || docs[i]['login_id']==null) {
            var zon=docs[i]['zone']+'@oditeksolutions.com';                     
            TempCollection.findOneAndUpdate({$or:[{login_id:null},{login_id:''}]},{$set:{login_id:zon}},{new:true},function(err1,upd){
                    if(!err1){
                        updateArr.push(upd);

                    }
           })

       }
    }
    console.log('lrn::',updateArr.length);
    if (updateArr.length > 0) {
        createAllocation();
        createUser();
    }
})

Here I need after all documents updated both function (i.e-createAllocation and createUser) to be called. Here before updating all document both are executing.

halfer
  • 19,824
  • 17
  • 99
  • 186
satya
  • 3,508
  • 11
  • 50
  • 130

1 Answers1

1

findOneAndUpdate runs asynchronously, so when the loop ends, the functions will not have done their job yet.

I recommend you to use async / await so you can easily run both steps synchronously (first the database updates and then call the functions at the end):

var updateArr=[];
TempCollection.find({}, async function(err, docs) {
    for(var i = 0; i < docs.length; i++) {
        if (docs[i]['login_id'] === '' || docs[i]['login_id'] == null) {
            var zon = docs[i]['zone'] + '@oditeksolutions.com'                     
            try {
                var upd = await TempCollection.findOneAndUpdate({ $or: [{ login_id: null }, { login_id: '' }]}, { $set: { login_id: zon }}, { new: true }).exec()
                updateArr.push(upd)
            } catch(err1) {
                console.log(err1) // throw err1
            }
        }
    }
    console.log('lrn::',updateArr.length);
    if (updateArr.length > 0) {
        createAllocation();
        createUser();
    }
})
Miguel Calderón
  • 3,001
  • 1
  • 16
  • 18