如何在猫鼬中添加特定模式类型的数组?

时间:2021-03-02 02:59:37

标签: javascript node.js mongoose mern

我想将该问题模式添加为 topicSchema 中问题数组中的类型,但不能这样做,因为它会出错。如何添加特定架构类型的数组。有办法吗?

const question_schema = require('./Question')

const topicSchema = new Schema(
  {
    name: {
        type: String,
        required: true,
        enum: [...Object.values(topics_enum)]
    },
    icon: {
        type: String,
        required: true
    },
    questions: [question_schema]
  },
  {
    versionKey: false,
  }
);

module.exports = mongoose.model("topics", topicSchema);

2 个答案:

答案 0 :(得分:0)

据我所知,使用 type 和 ref, 您需要使用这种格式来引用架构本身:

questions: [{
        type: Schema.Types.ObjectId,
        ref: 'question_schema'
    }
],

类型 (Schema.Types.ObjectId) 将为数组中的每个问题添加对象 ID(然后您可以稍后迭代以通过这些 ID 查找每个问题),并且引用 ('question_schema') 允许 {{1 }} 找出它应该引用的模式。只要 ref 与您的变量名称相同,它就应该使用 ref 连接。

答案 1 :(得分:0)

您需要将对象的类型声明为数组,请尝试:

questions:{
   type: [question_schema],
}
相关问题