简体   繁体   English

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

[英]how to add array of particular schema type in mongoose?

i want to add that question schema as the type inside that questions array in topicSchema, but cant do that as it gives error.我想将该问题模式添加为 topicSchema 中该问题数组中的类型,但不能这样做,因为它会给出错误。 How can i add array of particular schema type.如何添加特定模式类型的数组。 Is there a way?有办法吗?

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);

To my understanding, use type and ref, you need to use this formatting in order to reference the schema itself:据我了解,使用 type 和 ref,您需要使用这种格式来引用架构本身:

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

The type (Schema.Types.ObjectId) will add the object id for each question in the array (which you can then iterate over later to find each question by those IDs), and the ref ('question_schema') allows mongoose to figure out which of your schemas it should be referencing.类型(Schema.Types.ObjectId)将为数组中的每个问题添加 object id(然后您可以稍后对其进行迭代以通过这些 ID 查找每个问题),并且 ref ('question_schema')允许mongoose找出它应该引用您的哪个模式。 As long as the ref is the same as your variable name, it should connect using ref.只要 ref 与您的变量名称相同,它就应该使用 ref 连接。

You need to state the type of the object as an array, try:您需要将 state 的类型 object 作为数组,尝试:

questions:{
   type: [question_schema],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM