You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mongoose的findByIdAndUpdate更新文档时,移除grades数组中子文档自动生成_id的方法

解决Mongoose更新grades数组时自动生成_id的问题

这问题我之前也碰到过!Mongoose默认会给嵌套在数组里的子文档自动生成_id字段,要解决这个很简单,只需要在你的grades子对象定义里加上_id: false配置就行。

具体修改步骤

找到你的restaurantSchema定义,把grades数组里的子Schema配置修改成下面这样:

const { Schema, model } = require("mongoose");
const restaurantSchema = new Schema({
  address: {
    building: String,
    coord: [Number],
    street: String,
    zipcode: String
  },
  borough: String,
  cuisine: String,
  grades: [
    {
      _id: false, // 加上这一行,禁用自动生成_id
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
    }
  ],
  name: String,
  restaurant_id: String
})
exports.Restaurant = model("restaurant", restaurantSchema);

为什么这样能解决问题?

Mongoose对于数组中的嵌套对象,默认会将其当作子文档处理,而子文档的特性之一就是自动生成唯一的_id标识。通过在子对象的Schema配置中显式设置_id: false,就能告诉Mongoose不要为这些子对象生成_id字段。

验证效果

修改完Schema之后,再执行你原来的findByIdAndUpdate操作,返回的grades数组就会和你期望的格式一致,不再包含额外的_id字段了。

另外提一句:这个配置是持久化的,之后任何新增或更新grades数组的操作,都会遵循这个规则,不用每次更新都额外处理数据。

内容的提问来源于stack exchange,提问作者rkarisan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 12:12:32