代码之家  ›  专栏  ›  技术社区  ›  c-chavez

Mongodb updateone和$set和$currentDate在第二次更新后抛出错误代码40

  •  0
  • c-chavez  · 技术社区  · 7 年前

    我正在使用node和mongodb,我想更新一个文档并添加修改日期。我在第二次更新时遇到问题。第二次失败的具体原因是:

    • 首次修改会添加具有正确值的“lastModified”字段。
    • 第二次修改必须用当前日期更新“lastModified”字段,但失败。

    显示的错误为:

    {“driver”:true,“name”:“MongoError”,“index”:0,“code”:40,“errmsg”:“更新路径'lastModified'将在'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",
    

    有什么可能出错的建议吗?

    编辑:

    1 回复  |  直到 7 年前
        1
  •  2
  •   c-chavez    7 年前

    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',这是update操作符中属性的冲突。在这种情况下,它与$set中的另一个属性冲突,因此如果有人遇到这种情况,请检查您是否没有在同一命令中更新同一属性两次。

    完整的 Mongodb Error Code List is available here 但显然没有关于这些代码的描述或问题的官方文件(显然是用 this commit ).

    这就解决了问题。 感谢@Greg指出了正确的方向。