This content originally appeared on DEV Community and was authored by Akshat Singhania
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;
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
mongoose
.connect('connection url', {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true, //make this true
autoIndex: true, //make this also true
})
.then(() => {
console.log('Connected to mongoDB');
});
Thanks for reading, hearts ❤️ , and unicorns ? if you liked it, follow if you loved it
This content originally appeared on DEV Community and was authored by Akshat Singhania

Akshat Singhania | Sciencx (2021-05-15T15:07:18+00:00) Mongoose Unique Not Working. Retrieved from https://www.scien.cx/2021/05/15/mongoose-unique-not-working/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.