Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose field not required but unique [duplicate]

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

like image 903
Nicola Pedretti Avatar asked Dec 13 '22 22:12

Nicola Pedretti


1 Answers

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/

like image 68
Sam Quinn Avatar answered Dec 21 '22 09:12

Sam Quinn