【问题标题】:how to fix duplicate key error collection friends如何修复重复键错误收集朋友
【发布时间】:2019-07-31 23:58:17
【问题描述】:

我收到以下错误:

E11000 duplicate key error collection: db.users index: friends.userid_1 dup key: { : null }

我不知道如何解决这个问题。默认情况下它什么都没有,但是当我在friends 中输入没有任何内容的新用户ID 时,我仍然收到错误消息。为什么?

在用户架构中:

   friends : [
        {
            userid : {type: String, default: '', index: { unique: true }},
        }
    ],
    friendRequests: [
        {
            userid : {type: String, default: '', index: { unique: true }},
        }
    ]

【问题讨论】:

标签: javascript mongodb mongoose duplicates mongoose-schema


【解决方案1】:

根据猫鼬官方documentation

数组之所以特殊,是因为它们隐含的默认值为 [](空数组)。

这就是为什么当您在 friends 中不输入任何内容时它会隐式索引 null 值的原因。要解决此问题,您可以将两个数组的 default 值显式定义为 undefined 并将索引创建为 sparse 以从 unique 约束中排除空值,请尝试:

friends : {
    type: [ { userid : {type: String, default: '', index: { unique: true, sparse: true } } } ],
    default: undefined
},
friendRequests: {
    type: [ { userid : {type: String, default: '', index: { unique: true, sparse: true } } } ],
    default: undefined
}

编辑:请确保猫鼬在测试之前重建您的索引

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2021-06-02
    • 2021-10-25
    • 2021-11-04
    • 2021-09-20
    • 2015-07-12
    相关资源
    最近更新 更多