猫鼬中的多个子文档

时间:2020-03-30 20:28:52

标签: mongodb mongoose mongoose-schema

Mongoose是否可能有多个不同的子文档?我正在创建用于在线测试的应用程序,每个测试都将具有包含不同问题类型的问题数组,例如,真/假,多项选择,匹配等...我想创建不同的问题模式和问题数组以包含所有问题。例如questions: [QuestionSchema1, QuestionSchema2]。有可能这样做吗?

模式示例,其基本问题类型如下。如果我想为此测试添加其他类型的问题呢?

const testSchema = new mongoose.Schema({
  name: {
    type: String
  },
  level: {
    type: String
  },
  questions: [
    {
      id: {
        type: String
      },
      question: {
        type: String
      },
      answers: [
        {
          id: {
            type: String
          },
          answer: {
            type: String
          }
        }
      ],
      validAnswerId: {
        type: String
      }
    }
  ]
});

1 个答案:

答案 0 :(得分:0)

如果您真的想对子文档执行此操作,则可以将问题键入为对象数组,然后将所需的内容放入其中:

...
questions: [{
  type: Object
}],
...

如果您可以创建多个集合,可以使用猫鼬refPath来使用更严格的模式:

...
questions: [{
  question: {
    type: ObjectId,
    refPath: 'questions.questionType'
  },
  questionType: {
    type: String,
    enum: ['MultipleChoice', 'Matching', ...]
 },
}]
...

然后,您可以创建所有想要的问题模式,并将其模型(例如'MultipleChoice''Matching')添加到questionType枚举中。然后,当您需要访问问题时,只需在查询对象上用.populate('questions')填充问题即可。