'Unique validation not working in Mongoose
I recognized this question has been asked before, but none of the solutions seemed to work for me.
I have a simple model I'm defining like this:
const mongoose = require('mongoose')
const { Schema } = mongoose
let subscriberSchema = new Schema({
firstName: { type: String, required: true },
email: { type: String, required: true, unique: true }
}, { timestamps: true })
let Subscriber = mongoose.model('Subscriber', subscriberSchema)
If I run the following (in the REPL, so no async issues), I'd expect to see an error being logged for the second call to create.
Subscriber.create({ firstName: "Landon", email: "[email protected]" })
Subscriber.create({ firstName: "Landon", email: "[email protected]" }, function(err) {
console.log("ERROR", err)
})
Instead, I see "ERROR" null.
If I run a count query or a find query, I can see both models were created. What am I doing wrong?
Edit
Here are a few of the things I've already tried:
- Restart MongoDB after adding index
- Removing all of the existing records so there are no existing records that could violate the uniqueness constraint
- Defining the
emailattribute all of these ways (I've seen different implementations in different places):{ type: String, required: true, unique: true },{ type: String, required: true, index: true, unique: true },{ type: String, required: true, index: { unique: true } }.
Solution 1:[1]
Actually, unique option for validation working,how?Follow these steps:
1)set unique: true for certain field in schema(example "email")
2)drop whole db
3)restart node server
4)test in postman and you will see than now works
Cheers.
Solution 2:[2]
Make autoIndex: true while connecting to the database.
mongoose
.connect('connection url', {
useUnifiedTopology: true,
useNewUrlParser: true,
autoIndex: true, //make this true
})
.then(() => {
console.log('Connected to mongoDB');
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yunnosch |
| Solution 2 | Abdullah Alassaf |
