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

如何编写Mongoose Schema以存储嵌套对象结构

Mongoose嵌套对象Schema编写方案

你可以通过定义嵌套子Schema来实现目标存储结构,具体代码如下:

1. 定义单个选项的子Schema

先编写每个basicN对应的子结构Schema,匹配你需要的ischecked和ans字段:

const AnswerItemSchema = new mongoose.Schema({
  ischecked: {
    type: Boolean,
    default: false // 和示例默认值保持一致
  },
  ans: {
    type: String,
    default: "" // 默认空字符串
  }
});

2. 编写主Schema的answers字段

在你的BasicQ模型中,把answers字段定义为包含指定键的嵌套对象,每个键使用上面的子Schema:

const BasicQ = mongoose.model("basicq", new mongoose.Schema({
  userid: {
    type: mongoose.Types.ObjectId,
    required: true,
    ref: "Users",
  },
  answers: {
    basic1: AnswerItemSchema,
    basic2: AnswerItemSchema,
    basic3: AnswerItemSchema,
    basic4: AnswerItemSchema,
    basic5: AnswerItemSchema,
    // 若后续需要新增未知键,可开启下面配置(会失去字段校验能力)
    // type: Object,
    // strict: false
  }
}));

效果说明

这样定义后,MongoDB中存储的数据结构会完全符合你的要求:每个answers下的basicN都会自动带上默认的ischecked: false和ans: "",也支持后续修改这些字段的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:13:13