Reputation: 872
I have my example mongoose schema as below
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const exampleSchema = new Schema ({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
mobile:{
type: String,
required: true,
unique: true
}
})
module.exports ={Driver: mongoose.model('Driver', driverSchema)}
Now the thing is that unique in mobile is working fine, but in email it allows me to insert duplicate email address.
Upvotes: 0
Views: 223
Reputation: 872
It was due to I have records in collection before giving unique: true
.
Upvotes: 0
Reputation: 17888
You had better to create your indexes in mongodb shell.
In the mongoose docs they state:
In a production environment, you should create your indexes using the MongoDB shell rather than relying on mongoose to do it for you. The unique option for schemas is convenient for development and documentation, but mongoose is not an index management solution.
So I would remove unique options in schema, and can create the unique indexes in mongodb shell like this:
db.drivers.createIndex( { "email": 1 }, { unique: true } )
db.drivers.createIndex( { "mobile": 1 }, { unique: true } )
Upvotes: 1