使用唯一字段重复键错误集合

时间:2016-09-26 08:55:24

标签: javascript node.js mongodb mongoose

我在第二次尝试插入没有昵称的文档时收到MongoDB错误。该文档已具有唯一字段且不需要。

这是我的Mongoose模型:

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 }

1 个答案:

答案 0 :(得分:1)

所以我向上看了#34; 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

问题在于文档明确指出:

  

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

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

  

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

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