I have one schema like this:
export const HotelSchema = new mongoose.Schema({
name: String,
firstName: String,
email: { type: String, unique: true },
canLogin: Boolean
},
{
collection: "hotels"
}
);
and to add/update I am using this query:
this.hotelModel.updateOne({ _id: hotel._id }, hotel, { upsert: true });
Where hotel object I am passing:
{
"email" : "[email protected]",
"name" : "sunny123"
}
But it is inserting duplicate emails with _id
as null:
Even I tried findOneAndUpdate
. tried autoIndex
in the email schema. Still not working.
Am I missing something?
2
Answers
See https://mongoosejs.com/docs/validation.html#the-unique-option-is-not-a-validator
Infact, you should use unique index on a field. That works!
You are passing email and name, but you are not passing "_id", so "hotel._id" will not be found. Instead you should do as follows: