Mongoose Unique Not Working?!

Say we want the email field on our User model to be unique, so we set the Schema to be:

const UserSchema = new Schema({
email: {type: String, required: true, unique: true}

Somehow, it just doesn’t work. As it turns out, there are plenty of reasons why this wouldn’t work. Let’s see which one got you.


1. DB already messed up

If there are already duplicated emails in your collections, then the new constraints won’t work.

Fix the already duplicated ones in your db first.


2. Index creation takes time

For uniqueness to be ensured, mongo needs to create its index. Make sure that before you create any users, its index is already created.

const UserSchema = new Schema({
email: {type: String, required: true, unique: true}

const User = mongoose.model('User', UserSchema);

User.init().then(() => {
// safe to create users now.

Or simply export the init and await for the finish before starting tests:

// models/User.js
module.exports = mongoose.model('User', UserSchema).init();

// tests/config.js
before(async () => {
await require('../models/User');


3. You dropped your DB/Collection

When you’re testing, you end up resetting your database or collection by dropping them. However, remember that their indexes will be dropped at the same time, and they do not automatically rebuild.

So in tests that are not humungous, instead of dropping, consider doing:


Which clears out the collection.


7 thoughts on “Mongoose Unique Not Working?!

  1. Abdullah says:

    Thank you for clear explanation.
    1. DB already messed up.(result=>
    There were duplicate “email” on db. I removed them but it didn’t work.

    User.collection.deleteMany({}); this worked for me.

  2. MAS says:

    Deleting complete collection works. However, deleting duplicate records doesnt. My collection consists of many documents. Any other way without deleting the whole collection?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.