MongoDB 不允许用于在单个操作中替换数组中的项。相反,这是一个拉,然后是一个推操作。
不幸的是,在并行请求(分布式环境)上,我们在数组中的同一项上有一个竞争条件,即先运行2次拉,然后是2次推送。这会导致重复的条目,例如。
{
"_id": ...,
"nestedArray": [
{
"subId": "1"
},
{
"subId": "1"
},
{
"subId": "2"
}
]
}有什么解决办法吗?
发布于 2017-04-11 07:34:28
对于这种情况,我通常使用乐观锁。为此,您需要向模型中添加一个version字段,每次修改该模型时都会增加该字段。然后使用以下方法:
Model.findOneAndUpdate(
{$and: [{_id: <current_id>}, {version: <current_version>}]},
{nestedArray: <new_nested_array>})
.exec(function(err, result) {
if(err) {
// handle error
}
if(!result) {
// the model has been updated in the mean time
}
// all is good
});这意味着您首先需要获得模型并计算新的数组<new_nested_array>。通过这种方式,您可以确保对某个版本只进行一次修改。希望我能解释清楚。
https://stackoverflow.com/questions/43336426
复制相似问题