DEV Community

Cover image for Mongoose Unique Not Working
Akshat Singhania
Akshat Singhania

Posted on

Mongoose Unique Not Working

You have a user schema and you want the email field to be unique

import { Schema } from 'mongoose';

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

export default user schema;
Enter fullscreen mode Exit fullscreen mode

but it doesn't work! , here are some reasons because which this wouldn't work

1. Duplicate documents already created in DB before defining this property

You might have already added some duplicate data in the database so mongoose and MongoDB simply doesn't check unique field because it's already messed up

Delete the messed data from the MongoDB collections page to solve it

2. Auto Indexing or Create index is false

If you wouldn't have specified to auto index the data
which means to check for uniqueness, mongoose wouldn't do that

Simply make them to true while connecting to the database

    .connect('connection url', {
        useUnifiedTopology: true,
        useNewUrlParser: true,
        useCreateIndex: true, //make this true
        autoIndex: true, //make this also true
    .then(() => {
        console.log('Connected to mongoDB');
Enter fullscreen mode Exit fullscreen mode

Thanks for reading, hearts ❤️ , and unicorns 🦄 if you liked it, follow if you loved it

Discussion (0)