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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With