mongoDB/mongoose: unique if not null

As of MongoDB v1.8+ you can get the desired behavior of ensuring unique values but allowing multiple docs without the field by setting the sparse option to true when defining the index. As in:

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

Or in the shell:

db.users.ensureIndex({email: 1}, {unique: true, sparse: true});

Note that a unique, sparse index still does not allow multiple docs with an email field with a value of null, only multiple docs without an email field.

See http://docs.mongodb.org/manual/core/index-sparse/

Leave a Comment