Node.js 如何使用upsert行为正确更新文档?(Mongo bug服务器-10711)
我正在尝试更新一个文档,如果找到了更新,请插入其他内容 这就是我正在尝试的(使用sails水线ORM,它使用monodb节点驱动程序): 但这并没有奏效:Node.js 如何使用upsert行为正确更新文档?(Mongo bug服务器-10711),node.js,mongodb,sails.js,mongodb-query,waterline,Node.js,Mongodb,Sails.js,Mongodb Query,Waterline,我正在尝试更新一个文档,如果找到了更新,请插入其他内容 这就是我正在尝试的(使用sails水线ORM,它使用monodb节点驱动程序): 但这并没有奏效: code: 16836, err: 'Cannot update \'lfPoints\' and \'lfPoints\' at the same time' } null 我做错了什么 编辑 但我真的不想最终实现一个变通方法。如何应对?发生错误的原因是,当发生“upsert”时,和以及操作都试图在文档中设置项目。由于错误报告,您不能在一
code: 16836,
err: 'Cannot update \'lfPoints\' and \'lfPoints\' at the same time' } null
我做错了什么
编辑
但我真的不想最终实现一个变通方法。如何应对?发生错误的原因是,当发生“upsert”时,和以及操作都试图在文档中设置项目。由于错误报告,您不能在一次更新中使用两个不同的运算符修改文档的同一属性 然后,解决方案是“分离”更新,这样只有一个操作“仅”执行
$setOnInsert
,另一个操作将在匹配文档的位置执行其他更改。最好的方法是使用,以便将所有请求一次发送到服务器:
LineupPointsRecord.native(function (err,collection) {
var bulk = collection.initializeOrderedBulOp();
// Match and update only. Do not attempt upsert
bulk.find({
"teamId": lineUpPointsGeneralRecord.teamId,
"round": 0
}).updateOne({
"$inc": { "lfPoints": roundPoints },
"$push": { "roundPoints": roundPoints }
});
// Attempt upsert with $setOnInsert only
bulk.find({
"teamId": lineUpPointsGeneralRecord.teamId,
"round": 0
}).upsert().updateOne({
"$setOnInsert": lineUpPointsGeneralRecord
});
bulk.execute(function (err,updateResult) {
sails.log.debug(err,updateResult);
});
});
由于第二个操作只会在文档不匹配的地方尝试upsert,因此没有冲突,因为没有其他操作。在第一个操作中,这将“仅”在文档“确实匹配”的地方进行更改,并且由于此处没有尝试upsert,因此也没有冲突
确保您的是支持批量操作的最新版本,并且包含了最新的节点本机驱动程序。最新版本支持v2驱动程序,这一点很好
LineupPointsRecord.native(function (err,collection) {
var bulk = collection.initializeOrderedBulOp();
// Match and update only. Do not attempt upsert
bulk.find({
"teamId": lineUpPointsGeneralRecord.teamId,
"round": 0
}).updateOne({
"$inc": { "lfPoints": roundPoints },
"$push": { "roundPoints": roundPoints }
});
// Attempt upsert with $setOnInsert only
bulk.find({
"teamId": lineUpPointsGeneralRecord.teamId,
"round": 0
}).upsert().updateOne({
"$setOnInsert": lineUpPointsGeneralRecord
});
bulk.execute(function (err,updateResult) {
sails.log.debug(err,updateResult);
});
});