引用模式,而不是模型



我想引用一个定义为模式的子文档。下面是示例:

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

});

所以很明显,我想引用的问题和答案只是子文档作为模式,而不是模型。我如何引用它们?谢谢。

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

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

});

最新更新