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

在Mongoose/Node中如何为Survey的每个Answer生成ObjectId?

给Mongoose问卷Schema的每个Answer添加ObjectId

1. 修改Survey Schema定义

将answers从字符串数组改为子文档数组,每个子文档包含answer文本字段。Mongoose会自动为数组中的每个子文档生成_id,无需额外配置。

修改后的Schema代码:

const mongoose = require("mongoose");
const {User} = require("./User");

const SurveySchema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    title: {
        type: String,
        minLength: 5,
        maxlength: 100,
        required: true
    },
    // other fields///
    questions: [{
        question: {
            type: String,
            minLength: 10,
            maxlength: 200,
            required: true
        },
        answers: [{
            // 把原字符串类型改为子文档的answer字段
            answer: {
                type: String,
                minLength: 10,
                maxlength: 100,
                required: false
            }
            // Mongoose默认自动生成_id,无需手动声明
        }],
    }],
}, {timestamps: true} );

module.exports.Survey = mongoose.models.Survey || mongoose.model('Survey', SurveySchema);

2. 调整添加问题的代码

因为现在answers需要传入子文档对象(而非纯字符串),所以要把原字符串数组转换成包含answer字段的对象数组:

let survey = await surveyManager.getSurvey(surveyId);
// 将字符串数组转为子文档数组
let newQuestion = {
  question: question,
  answers: answers.map(text => ({ answer: text }))
};
survey.questions.push(newQuestion);
await survey.save();
return survey;

3. 修改后的数据结构示例

保存后,数据库中的每个answer都会自动生成独立的ObjectId,结构如下:

"questions" : [
  {
    "question" : "this is a question?",
    "answers" : [
          {
              "answer" : "answer number 1",
              "_id" : ObjectId("63a89d2e101149d7958e0f79")
          },
          {
              "answer" : "answer number 2",
              "_id" : ObjectId("63a89d2e101149d7958e0f7a")
          },
          {
              "answer" : "answer number 3",
              "_id" : ObjectId("63a89d2e101149d7958e0f7b")
          }
    ],
    "_id" : ObjectId("63a89d2e101149d7958e0f78")
  }
],

可选:手动控制_id生成

如果需要自定义_id的生成逻辑(比如手动指定),可以在answer子文档中显式声明_id字段:

answers: [{
    answer: {
        type: String,
        minLength: 10,
        maxlength: 100,
        required: false
    },
    _id: {
        type: mongoose.Schema.Types.ObjectId,
        auto: true // 保持自动生成,设为false则需手动传入
    }
}],

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:35:16