Mongodb unique sparse index

孤街醉人 提交于 2019-11-30 19:09:05
Rabbits

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!