【问题标题】:UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collectionUnhandledPromiseRejectionWarning: MongoError: E11000 重复键错误集合
【发布时间】:2021-03-04 05:18:51
【问题描述】:

我正在尝试更新文档数组中的对象

    "state": [],
    "users": [{
        "ready": false,
        "_id": {
            "$oid": "5fb810c63af8b34180912014"
        },
        "user": {
            "$oid": "5f81eb91d537dc3baf443a84"
        },
        "calification": 0
    }, {
        "ready": false,
        "_id": {
            "$oid": "5fb810ca3af8b34180912015"
        },
        "user": {
            "$oid": "5fa6f98f15e96c1125b905a9"
        },
        "calification": 0
    }],
    "test": {
        "$oid": "5f986af2baa88b2d30760961"
    },
    "__v": 1
}

我正在使用这个功能

updateUserState = async function(game_id,username){
    var user_id = '5fb7fae0c28f1d33a99b877e';
    await Game.findOneAndUpdate({_id: game_id, users: {$elemMatch: {user: user_id}}},
        {$set: { ready: true}}, 
        {'new': true, 'safe': true, 'upsert': true});
}

但我收到此错误

(node:16768) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: myproject.games index: _id_ dup key: { _id: ObjectId('5fb810c63af8b34180912013') }

我不知道为什么说密钥是重复的

【问题讨论】:

  • 因为game_id已经被其他人使用了
  • 但没有其他类似的 id

标签: javascript mongodb mongoose


【解决方案1】:
{upsert: true, new: true, runValidators: true}

你可以按照上面的方法试试

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2017-08-27
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2020-02-02
    • 1970-01-01
    • 2017-05-25
    相关资源
    最近更新 更多