Home > other >  Unique and id is getting null in Moongose update/upsert
Unique and id is getting null in Moongose update/upsert

Time:01-22

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?

CodePudding user response:

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!

CodePudding user response:

See,

You are passing email and name . But _id you are not passing so hotel._id will not be found. Instead you should do

this.hotelModel.updateOne({ email:hotel.email}, hotel, { upsert:true}); Or this.hotelModel.updateOne({ email:hotel.email}, hotel, { upsert:true},{new:true});

  • Related