Unique Rare Mongodb Index

I created a rare and unique index in my mongodb collection.

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

It was 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 no key set, I get 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 clues?

+7
source share
1 answer

I also had this problem. I wanted the value to be either null or unique. So, I set the unique and sparse flags:

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

And I made sure that the database really created the index correctly using 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 problem: mongo _id key duplication error )

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

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

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

+10
source

All Articles