gpt4 book ai didi

node.js - 带有 ids 数组的 mongoose findOneAndUpdate 回调

转载 作者:太空宇宙 更新时间:2023-11-04 01:11:26 24 4
gpt4 key购买 nike

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

我希望它返回它已创建或更新的所有对象 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);
}

最佳答案

我修饰了你的代码,让你知道什么时候发生了什么:

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

关于node.js - 带有 ids 数组的 mongoose findOneAndUpdate 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com