# Mongoose - Add a unique index  on an existing collection

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:

```typescript
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:

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

Otherwise your index will not be setup by MongoDB.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Don't forget to restart your MongoDB server to create the new index.</div>
</div>

## 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](https://www.mongodb.com/docs/manual/core/index-sparse/)

[Partial indexes - MongoDB Documentation](https://www.mongodb.com/docs/manual/core/index-partial/#std-label-index-type-partial)
