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

MongoDB Schema:插入仅传field1时如何设置子文档数组默认值?

How to Set a Default Value for field2 in Your MongoDB Schema

Hey there! Let's sort out how to set a proper default value for field2 in your MongoDB Schema. Right now, when you insert a document with only field1, field2 defaults to an empty array because that's MongoDB's implicit behavior for unspecified array fields. If you want to define a custom default (whether that's a pre-populated array or just explicitly declare the empty array), here's exactly what to do:

Option 1: Explicitly Set Default as an Empty Array

If you just want to make the empty array default explicit (to make your Schema more readable, even though MongoDB does this automatically), add the default property directly to field2:

{
  field1: { type: "String", trim: true },
  field2: {
    type: [{
      subField1: { type: "String" },
      subField2: { type: "Number", default: 0 }
    }],
    default: []
  }
}

Option 2: Default to a Pre-Populated Array with Subdocument(s)

If you want field2 to start with one or more subdocuments that use your defined sub-field defaults, use a function for the default (this avoids reference issues with non-primitive values):

Example with a single default subdocument:

{
  field1: { type: "String", trim: true },
  field2: {
    type: [{
      subField1: { type: "String", default: "default-sub-value" }, // Optional: add default for subField1
      subField2: { type: "Number", default: 0 }
    }],
    default: () => [{}] // Uses the sub-field defaults automatically
  }
}

When you insert a document with only field1, field2 will now be [{ subField1: "default-sub-value", subField2: 0 }] instead of an empty array.

Example with a custom pre-defined array:

If you want a specific array structure as the default, you can define it directly in the function:

{
  field1: { type: "String", trim: true },
  field2: {
    type: [{
      subField1: { type: "String" },
      subField2: { type: "Number", default: 0 }
    }],
    default: () => [
      { subField1: "first-item", subField2: 5 },
      { subField1: "second-item" } // subField2 will default to 0 here
    ]
  }
}

Key Tips:

  • Always use a function for default values that are objects or arrays (like default: () => [] instead of default: []). This ensures a fresh instance is created for each new document, preventing unintended shared references between documents.
  • If you don't specify a default for subField1, it will be undefined in the default subdocuments unless you explicitly set it in the array.

That's all you need to adjust your Schema to get the exact default behavior you want for field2!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:33:53