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

Mongoose子文档自动生成_id问题求助:移除account_charges中的_id

Why does Mongoose auto-generate _id for subdocuments in account_charges?

The Root Cause

This is Mongoose's default behavior: every subdocument (objects nested inside an array field) automatically gets an _id generated by default, even if you don't explicitly define it in your code. Mongoose treats each object in the account_charges array as a subdocument, and subdocuments are configured to have an _id field out of the box.

How to Disable Auto-Generated _id for Subdocuments

There are two reliable ways to fix this:

1. Explicitly Disable _id in Your Schema

The cleanest and most permanent solution is to update your AccountType schema to explicitly turn off _id generation for the subdocuments in account_charges. Here's how your schema should look:

const mongoose = require('mongoose');

const AccountTypeSchema = new mongoose.Schema({
  account_name: String,
  account_type: String,
  account_bin: String,
  account_charges: [{
    charge: Number,
    name: String,
    order: Number,
    reoccurence: Boolean,
    _id: false // This line disables auto-generated _id for subdocuments
  }]
});

const AccountType = mongoose.model('AccountType', AccountTypeSchema);

Once you add _id: false to the subdocument schema definition, Mongoose will no longer generate _id fields for entries in account_charges when saving.

If you can't modify the schema right now, you can manually override the _id field when building your subdocument objects:

let push_value = {
  charge : req.body.account_charge_value[x],
  name : req.body.account_charge_name[x],
  order : req.body.account_charge_order[x],
  reoccurence : req.body.account_charge_reoccurence[x],
  _id: undefined // Prevent Mongoose from generating an _id
}

Note that this approach is error-prone because you have to remember to add this line every time you create a subdocument, so updating the schema is strongly preferred.

Applying This to Your Code

In your current implementation, you didn't configure the account_charges subdocument schema to disable _id generation, which is why Mongoose automatically added those fields. Updating your Schema as shown in option 1 will resolve the issue permanently.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:06:35