Search code examples
mongodbmongoosemongoose-schema

Multiple subdocuments in Mongoose


Is it possible to have multiple different subdocuments is Mongoose ? I'm creating app for online tests , and each test will have questions array containing different question types , for example true/false , multiple choice, matching and etc ... I want to create different questions schemas and questions array to contain them all. For example questions: [QuestionSchema1, QuestionSchema2]. Is it possible to do so ?

Schema example with basic question type down below. And what if i want do add different type of question for this test ?

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

Solution

  • If you really want to do this with subdocuments you can just type the the questions as an object array and put whatever you want inside it:

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

    If you are fine with creating multiple collections you can use mongooses refPath to do this with stricter schemas:

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

    Then you can create all the different schemas you want for your questions and add their models (like 'MultipleChoice' and 'Matching') to the questionType enum. Afterwards when you need to access the questions you just populate them with .populate('questions') on the query object.