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
Top comments (5)
Hi from Nov 2022... neither of these worked for me, and it was because the indexes were being created in the background and I was seeding data as soon as a connection was established. This meant the data was added before the indexes were created, and apparently even though there was no duplicate, the indexes would not be created once this happens. There are two ways I know of to solve this:
The first- and best imho- is to use mongoose.connection.syncIndexes() to reconstruct the indexes of all collections to match all schemas (it will even create collections for you in the process), and only when this is complete (.then() or await) do you seed data or process requests.
An alternative is to use mongoose.model.createIndexes() to create indexes for the specific models you want to ensure indexes for; you also have to do this before seeding/processing.
Apparently there was an ensureIndexes() method to similar effect that was deprecated.
xyz
xyz
maybe I find a better way.
there is a package that can help easily.
Thanks it worked for me. the DB already have duplicate data that was why it was not working