【问题标题】:Duplicate key error collection with unique field具有唯一字段的重复键错误集合
【发布时间】:2017-02-03 12:57:46
【问题描述】:

我在第二次尝试插入没有昵称的文档时遇到 MongoDB 错误。文档已经有唯一的字段并且不是必需的。

这是我的猫鼬模型:

var schema = new Schema ({

        username: {
            type: String,
            required: false
        },

        nickname: {
            type: String,
            required: false,
            unique: true,
            trim: true
        },

        status: {
            type: String,
            required: false,
            trim: true,
            minlength: 1,
            maxlength: 100
        },

        avatar: String,

        online: {
            type: Boolean,
            default: false
        },

        created: {
            type: Date,
            default: Date.now
        },

        device: {
            type: ObjectId,
            ref: 'Device',
            required: false
        },

        createdRooms:[{
            type: Schema.Types.ObjectId,
            ref: 'Room'
        }],

        facebook: {
            facebookToken: {
                type: String,
                required: false,
                trim: true,
                unique: false
            },

            facebookId: {
                type: String,
                required: false,
                trim: true,
                unique: false
            }
        }
    },

    {
        toObject: {
            virtuals: true
        },
        toJSON: {
            virtuals: true
        }

});

第一次将没有昵称的文档添加到数据库,但是当我想保存另一个没有昵称的文档时,我得到一个错误:

MongoError: E11000 duplicate key error collection: grooptag.users index: nickname_1 dup key: { : null }

【问题讨论】:

  • 昵称不是必须的而是唯一的问题吗?
  • @NadiaCerezo 是的,但是如何确保该字段是唯一的并且不是必需的?

标签: javascript node.js mongodb mongoose


【解决方案1】:

所以我查找了“MongoDB 不是必需的但唯一的”,我发现了这个:mongoDB/mongoose: unique if not null

看来你需要使用sparse: true 而不是required: false 才能得到你想要的。

编辑:阅读有关稀疏索引的 MongoDB 文档,但是,我被重定向到部分索引,这似乎是从 MongoDB 3.2 开始的方式:https://docs.mongodb.com/manual/core/index-partial/#index-type-partial

问题在于,虽然文档明确指出:

部分索引代表稀疏索引提供的功能的超集,应该优先于稀疏索引。

稀疏索引和唯一索引似乎不是这样,因为它们也在同一页面上声明:

如果文档不满足过滤条件,具有唯一约束的部分索引不会阻止插入不满足唯一约束的文档。

自相矛盾的方式...:/

【讨论】:

  • 谢谢,我会检查并通知您。
  • 这对我不起作用。似乎“稀疏”仅适用于引用类型字段。
  • 奇怪,docs.mongodb.com/manual/core/index-sparse 此处的文档指出:既稀疏又唯一的索引可防止集合包含具有字段重复值的文档,但允许多个文档省略键。这听起来正是您想要的,对吧?
  • 没错,但我刚刚检查了我的模型,但它不起作用。您在 cmets 中附加的链接说它不起作用。一位评论员说:“不适用于缺少的字段也许行为在更高版本的 mongodb 中发生了变化,应该更新答案。”它现在看起来是我的领域:nickname: { type: String, sparse: true, index: true, unique: true, trim: true }
  • 你是对的,稀疏索引似乎已经被弃用了......耻辱。
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 2015-08-07
  • 2014-09-15
  • 1970-01-01
相关资源
最近更新 更多