简体   繁体   中英

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. 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:

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. As long as the ref is the same as your variable name, it should connect using ref.

You need to state the type of the object as an array, try:

questions:{
   type: [question_schema],
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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