Mongodb unique sparse index

前端 未结 1 455
有刺的猬
有刺的猬 2021-01-04 10:24

I have created a sparse and unique index on my mongodb collection.

var Account = new Schema({
                email: { type: String, index: {unique: true, s         


        
相关标签:
1条回答
  • 2021-01-04 11:12

    I just had this issue too. I wanted a value to either be null or be unique. So, I set both the unique and the sparse flags:

    var UserSchema = new Schema({
      // ...
      email: {type: String, default: null, trim: true, unique: true, sparse: true},
      // ...
    });
    

    And, I made sure that the database had actually created the index correctly with db.users.getIndexes();

    {
      "v" : 1,
      "key" : {
        "email" : 1
      },
      "unique" : true,
      "ns" : "test.users",
      "name" : "email_1",
      "sparse" : true,
      "background" : true,
      "safe" : null
    },
    

    (So, this is not the same as the issue here: mongo _id field duplicate key error)

    My mistake was setting the default value to null. In some sense, Mongoose counts an explicit null as a value that must be unique. If the field is never defined (or undefined) then it is not enforced to be unique.

    email: {type: String, trim: true, unique: true, sparse: true},
    

    So, if you are having this issue too, make sure you're not setting default values, and make sure you're not setting the values to null anywhere else in your code either. Instead, if you need to set it explicitly, set it to undefined (or a unique value).

    0 讨论(0)
提交回复
热议问题