Referencing a schema, not a model

Issue

I want to reference to a subdocument which is defined as a schema. Here’s the example:

exam.model.js:

const answerSchema = new mongoose.Schema({
    text: String,
    isCorrect: Boolean,
});

const questionSchema = new mongoose.Schema({
    text: String,
    answers: [answerSchema],
});

const examSchema = new mongoose.Schema({
    title: String,
    questions: [questionSchema],
})

const ExamModel = mongoose.model("Exam", examSchema);

//...export the schemas and ExamModel...

solvedExam.model.js:

const solvedExamSchema = new mongoose.Schema({
    exam: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Exam",
    }
    answers: [{
        question: {
            type: mongoose.Schema.Types.ObjectId,
            ref: //What do I put here? "question" is not a model, it's only a sub-document schema
        }
        answer: {
            type: mongoose.Schema.Types.ObjectId,
            ref: //Same problem
        }
    }],
    
});

So as it’s obvious, I want to reference to the questions and answers which are only subdocuments as a schema and NOT models. How can I reference them? Thanks.

Solution

You should declare the respective Answer and Question Schema and refence those:

const answerSchema = new mongoose.Schema({
    text: String,
    isCorrect: Boolean,
});

const questionSchema = new mongoose.Schema({
    text: String,
    answers: [answerSchema],
});

const examSchema = new mongoose.Schema({
    title: String,
    questions: [questionSchema],
})

const AnswerModel = mongoose.model("Answer", examSchema);
const QuestionModel = mongoose.model("Question", examSchema);
const ExamModel = mongoose.model("Exam", examSchema);

...

const solvedExamSchema = new mongoose.Schema({
    exam: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Exam",
    }
    answers: [{
        question: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Question'
        }
        answer: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Answer'
        }
    }],
    
});

Answered By – lpizzinidev

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.