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
        }
    );
});
3
  • 1
    the async operation (Model.update) is executed after the for loop, always. Because there is nothing async inside your for loop. See: stackoverflow.com/questions/16336367/… Commented Mar 7, 2014 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? Commented Mar 7, 2014 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: blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop Commented Mar 7, 2014 at 11:54

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.