mongoosefindOneAndUpdate与ID数组callback

我在forEach循环中使用findOneAndUpdate来创build/更新多个条目。

我希望它返回一个数组,它已经创build或更新的所有对象ID。

在循环过程中,我可以看到它将数据添加到数组,但是一个离开循环,数组是空的。

该数组不应该填充?

这是我的代码。

var softwareArray = ["Software1","Software2","Software3"], updatedArray = []; softwareArray.forEach(function(software){ Software.findOneAndUpdate( { Name: software }, { Name: software }, {upsert:true}, function(err, rows){ updatedArray.push(rows._id); console.log(updatedArray); //This has data in it.... } ); }); console.log(updatedArray); //This has no data in it... 

编辑:更新我的工作变化为蒂亚戈

 var softwareArray = ["Software1","Software2","Software3"], updatedArray = []; loopSoftware(softwareArray, function(updatedArray){ console.log(updatedArray); //carry on.... } function loopSoftware(input, cb){ var returnData = []; var runLoop = function(software, done) { Software.findOneAndUpdate( {Name: software}, {Name: software}, {upsert:true},function(err, rows){ returnData.push(rows._id); done() } ); }; var doneLoop = function(err) { cb(returnData); }; async.forEachSeries(input, runLoop, doneLoop); } 

当然,这会发生 – 就像Node上的其他networking一样,它是asynchronous的!

这意味着您为findOneAndUpdate操作指定的callback在到达console.log(updatedArray);时尚未运行console.log(updatedArray); 码。

看看Q为解决这个共同的问题。

我装饰了你的代码,让你看到什么时候发生了什么:

 var softwareArray = ["Software1","Software2","Software3"], updatedArray = []; // TIMESTAMP: 0 softwareArray.forEach(function(software){ // TIMESTAMP: 1, 2, 3 Software.findOneAndUpdate( { Name: software }, { Name: software }, {upsert:true}, function(err, rows){ // TIMESTAMP: 5, 6, 7 updatedArray.push(rows._id); console.log(updatedArray); // This has data in it.... // want to use the result? if (updatedArray.length == softwareArray.length) { console.log(updatedArray); } } ); }); // TIMESTAMP: 4 console.log(updatedArray);