Mongoose - Add a unique index on an existing collection

The "sparse" option

·

1 min read

When you work with MondoDB you often use indexes to optimize your query.

If you want to create a unique index to prevent duplicated entries for a specific field (like email or username for example) on a new collection you can do it by adding the unique option for the field in your model:

email: { type: String, unique: true}

But if:

  • You create a new field in an existing collection or

  • There's already some document in your collection and you want to change the rules of a field

You have to set a default value and use the parse option:

email: { type: String, default: '', unique: true, parse: true}

Otherwise your index will not be setup by MongoDB.

💡
Don't forget to restart your MongoDB server to create the new index.

Details

The sparse option does not include all documents of a collection, only those that have the indexed field (even if the value is null) it basically check for non-empty value.

If you need to check more than the field existence I would suggest you take a look at Partial Indexes.

Sparse Index - MongoDB documentation

Partial indexes - MongoDB Documentation