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).
Rabbits
source share