引用模式,而不是模型

Referencing a schema, not a model

我想引用定义为架构的子文档。这是示例:

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

很明显,我想引用问题和答案,这些问题和答案只是作为模式而不是模型的子文档。我怎样才能引用它们?谢谢

您应该分别声明 AnswerQuestion Schema 并引用它们:

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