我在使用 Model.bulkWrite
更新插入我的文档时遇到困难。我在文档中没有发现任何内容表明这是不可能的(不过,也许我错过了)。以下是我正在使用的代码示例:
var opts = [];
for (var item of data){
opts.push({
updateOne: {
filter: {"id": item.id},
update: {"$setOnInsert": {
"id": item.id,
"name": item.name}
}
}
})
};
Item.bulkWrite(
opts,
{upsert: true},
function(err, result){
if(err) throw err;
console.log(result);
// do more stuff here
}
);
我通过循环运行多个更新/更新插入没有任何问题,但是当我这样做时,我将无法访问操作完成时的回调,因此这对我不起作用。我还测试了上述代码,将 updateOne
部分替换为 insertOne
部分,并且它可以正常工作。
有人知道发生了什么事吗? upsert 在这里不是一个有效的选项吗?
最佳答案
@Alex Blex,你说得对。我想这只是我的疏忽。对于那些感兴趣的人来说,这意味着从代码的第二部分中删除 upsert
并将第一部分更改为:
var opts = [];
for (var item of data){
opts.push({
updateOne: {
filter: {"id": item.id},
update: {"$setOnInsert": {
"id": item.id,
"name": item.name}
},
upsert: true
}
})
};
关于node.js - 使用bulkWrite 更新/更新插入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47099064/