6

I have an email field set as unique, but it is not required.

The problem is that if the user does not enter anything Mongoose puts "null" in it. This causes duplicates because every user that does not enter the email field will have "null" assigned to it.

What is the standard practice to avoid this?

Thanks

Nicola Pedretti
  • 4,831
  • 3
  • 36
  • 42

1 Answers1

18

Use a sparse unique index

If a document does not have a value for a field, the index entry for that item will be null in any index that includes it. Thus, in many situations you will want to combine the unique constraint with the sparse option. Sparse indexes skip over any document that is missing the indexed field, rather than storing null for the index entry.

db.collection.createIndex( { a: 1, b: 1 }, { unique: true, sparse: true } )

More information: https://docs.mongodb.com/v3.0/tutorial/create-a-unique-index/

Sam Quinn
  • 3,310
  • 1
  • 16
  • 11