唯一和id在moongoose更新/upsert中为空



我有一个这样的模式:

export const HotelSchema = new mongoose.Schema({
name: String,
firstName: String,
email: { type: String, unique: true },
canLogin: Boolean
},
{
collection: "hotels"
}
);

和添加/更新我使用这个查询:

this.hotelModel.updateOne({ _id: hotel._id }, hotel, { upsert: true });

我经过的酒店对象:

{
"email" : "er.markar@gmail.com",
"name" : "sunny123"
}

但是它正在插入重复的电子邮件,_id为空:

我甚至尝试了findOneAndUpdate。在电子邮件架构中尝试autoIndex。还是不行

我错过了什么吗?

参见https://mongoosejs.com/docs/validation.html#the-unique-option-is-not-a-validator

事实上,您应该在字段上使用唯一索引。那工作!

您正在传递电子邮件和姓名,但您没有传递">_id"所以">hotel._id"将不会被发现。相反,你应该这样做:

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

最新更新