1

What is the best way to ensure that the for loop completes its processing before updating the MongoDB database in this code snippet:

var userIdArray = [] // contains 100000 userIds

User.find({'_id': {$in: userIdArray}}, 'name', function(err, result){
    var thisTime = new Date().getTime();

    var usersArray = [];
    for (var i = 0; i < result.length; i++) {
        var user = result[i];
        var userObject = {
            userId: user['_id'],
            userName: user.name,
            time: thisTime
        }
        usersArray.push(userObject);
    };

    Model.update(id,
        {$pullAll: {userIds: userIdArray}, $push: {users: {$each: usersArray}}},
        function(err, result) {
            //continue to do stuff
        }
    );
});
AmpT
  • 2,146
  • 1
  • 24
  • 25
  • 1
    the async operation (`Model.update`) is executed **after** the for loop, always. Because there is nothing async inside your `for` loop. See: http://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node – Salvatorelab Mar 07 '14 at 10:28
  • @TheBronx Thank you for that! So if there was another MongoDB database call inside the for loop, would that change the situation? – AmpT Mar 07 '14 at 10:55
  • 1
    Of course `Model.update` will be executed after the **synchronous operations** in the loop, but not always after the async tasks you add inside. Node.js will "check" for completed async tasks once your synchronous code is executed (that is, once the `Model.update` task is **queued**) and will execute it's callbacks. You can read more about the **Event Loop** in Node.js here: http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ – Salvatorelab Mar 07 '14 at 11:54

1 Answers1

2

Your for loop has all sequential and synchronous operations. It will always complete before your mongo update is triggered.

Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37