【问题标题】:how to add array of particular schema type in mongoose?如何在猫鼬中添加特定模式类型的数组?
【发布时间】:2021-05-31 14:24:21
【问题描述】:

我想将该问题模式添加为 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);

【问题讨论】:

    标签: javascript node.js mongoose mern


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      questions:{
         type: [question_schema],
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-22
        • 2017-09-10
        • 2019-11-20
        • 1970-01-01
        • 2013-09-22
        • 2014-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多