使用FindByIdAndUpdate更新嵌套对象时自动生成_id问题求助
解决Mongoose更新嵌套字段时自动生成
_id的问题 问题原因
Mongoose默认会为所有嵌套的子文档(哪怕是匿名对象结构)自动生成_id字段,这就是你的result对象中多出_id的原因。
解决方案
在Schema的result嵌套结构中显式添加_id: false,禁用自动生成_id的行为:
const NotiticationSchema = new Schema<Notitication>({ title: { type: String, required: true }, description: { type: String, default: null }, date: { type: Date, default: Date.now() }, type: { type: String, required: true }, navigation: { type: String, enum: NotificationNav, required: true }, navigationId: { type: String, enum: NotificationIds, required: true }, teamId: { type: String, required: true }, result: { type: { accepted: { type: Boolean, required: true }, motivation: { type: String, required: true }, _id: false // 禁用子文档自动生成_id }, default: null } });
额外优化
另外注意,findByIdAndUpdate默认返回更新前的旧文档,如果需要获取更新后的文档,需添加{ new: true }选项:
const notification = await NotiticationModel.findByIdAndUpdate( req.params["id"]!, { $set: { result: { accepted: true, motivation: null } } }, { new: true } // 返回更新后的文档 );
修改后,更新的result字段就会符合预期格式,不会再出现多余的_id。
内容的提问来源于stack exchange,提问作者Loris Cuntreri
相关产品推荐
相关产品推荐

