NodeJS

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.

O_O

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.

>O_O

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');
});

O_O

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:

User.collection.deleteMany({});

Which clears out the collection.

Standard

One thought on “Mongoose Unique Not Working?!

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.