我正在使用node和mongodb,我想更新文档并添加修改日期。我在第二次更新时遇到了问题。第二次失败的具体情况是因为:
- 文档已存在,但没有“lastModified”字段。
- 第一次修改会添加具有正确值的“lastModified”字段。
- 第二次修改必须使用当前日期更新“lastModified”字段,但会失败。
显示的错误是:
{"driver":true,"name":"MongoError","index":0,"code":40,"errmsg":"Updating the path 'lastModified' would create a conflict at 'lastModified'"},"params":null}}
mongo中的文档是:
{
_id" : ObjectId("5af07316fc5f13c574ba825b"),
"field1" : "value1"
}
我的更新代码是:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let url = 'some mongo url';
let database = 'some database';
let newData = {'field1':'newValue1'}
(async function() {
let client;
try {
client = await MongoClient.connect(url , {useNewUrlParser: true});
let database = client.db(database);
let result = await database.collection(collection).updateOne(filter, {
$set: newData,
$currentDate: {'lastModified': true}
});
assert.equal(1, result.matchedCount);
assert.equal(1, result.modifiedCount);
// Close connection
client.close();
} catch (err) {
console.log(err.stack);
}
// Close connection
client.close();
})();
第一次更新后,数据库中的文档是:
{
_id" : ObjectId("5af07316fc5f13c574ba825b"),
"field1" : "value1",
"lastModified" : ISODate("2018-09-07T23:18:21.485Z")
}
这是正确的。 我第二次尝试更新时失败。
我正在使用:
"mongodb": "^3.1.4",
"node": "^10.10.0",
对可能出现的问题有什么建议吗?
编辑:
第一次更新后,从数据库中取出数据,然后执行第二次更新。
最佳答案
抛出该错误是因为 $set 中的对象包含一个也将由 $currentDate 设置的属性。解决方案是确保该属性在 newData 中不存在(如果该属性将由任何 update operator 设置) .
在这种情况下,在更新之前,清理 newData 并确保它没有属性 lastModified,因为它将被更新运算符 $currentDate 修改:
...
// remove any property that will be used by update operators
if (newData && newData.hasOwnProperty('lastModified')) {
delete newData['lastModified'];
}
let result = await database.collection(collection).updateOne(filter, {
$set: newData,
$currentDate: {'lastModified': true}
});
...
Mongodb错误代码40
错误代码 40 指的是“ConflictingUpdateOperators”,这是更新运算符中的属性冲突。在这种情况下,它与 $set 中的另一个属性发生冲突,因此如果任何人发生这种情况,请检查您是否没有在同一命令中两次更新同一属性。
完整Mongodb Error Code List is available here但显然没有关于这些代码的描述或问题的官方文档(显然已被 this commit 删除)。
这解决了这个问题。 感谢@Greg 指出了正确的方向。
关于node.js - Mongodb updateone 与 $set 和 $currentDate 在第二次更新后抛出错误代码 40,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52237083/