skip to Main Content

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


  1. 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!

    Login or Signup to reply.
  2. 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:

    this.hotelModel.updateOne({ email:hotel.email}, hotel, { upsert:true});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search