Mongodb unique sparse index

為{幸葍}努か 提交于 2019-11-30 03:19:07

问题


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

var Account = new Schema({
                email: { type: String, index: {unique: true, sparse: true} },
                        ....

It has been created correctly:

{ "ns" : "MyDB.accounts", "key" : { "email" : 1 }, "name" : "email_1", "unique" : true, "sparse" : true, "background" : true, "safe" : null }

But if I insert a second document with a key not set I receive this error:

{ [MongoError: E11000 duplicate key error index: MyDB.accounts.$email_1  dup key: { : null }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: MyDB.accounts.$email_1  dup key: { : null }',
  code: 11000,
  n: 0,
  ok: 1 }

Any hints?


回答1:


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



来源:https://stackoverflow.com/questions/17125089/mongodb-unique-sparse-index

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