简体   繁体   English

如何使用MongoDB和node.js处理异步?

[英]How to handle async with MongoDB and node.js?

What is the best way to ensure that the for loop completes its processing before updating the MongoDB database in this code snippet: 在以下代码片段中更新MongoDB数据库之前 ,最好的方法是确保for循环完成其处理:

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

Your for loop has all sequential and synchronous operations. 您的for循环具有所有顺序和同步操作。 It will always complete before your mongo update is triggered. 它始终会在触发mongo更新之前完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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