【发布时间】:2021-03-18 18:25:55
【问题描述】:
我正在尝试在 mongoose 中使用引用,但不知何故无法正确执行。
我正在努力实现的目标
我想查询examModel 并获取有关特定考试的所有信息,包括与该考试相关的问题。
我的成就
新问题被保存到questionModel 中,考试的对象ID 正在保存问题,但是examModel 的questions 数组没有注意到它。
我有两种不同的型号:
examModel
const examSchema = new mongoose.Schema({
examId: {
type: String,
unique: true,
index: true,
required: true,
default: _generateAlphanumericId(18),
},
questions: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Questions",
}],
}, {
timestamps: true,
});
module.exports = mongoose.model("Exams", examSchema);
问题模型
const questionSchema = new mongoose.Schema({
_refExamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Exams",
},
questionId: {
type: String,
unique: true,
index: true,
required: true,
default: _generateAlphanumericId(26),
},
title: {
type: String,
trim: true,
required: [true, "Question is missing"],
},
}, {
timestamps: true,
});
module.exports = mongoose.model("Questions", questionSchema);
现在,当我将新问题保存到问题模型中时,我会从考试模型中发送考试的_id,但exam model 的questions 数组仍然不会保存新创建问题的对象ID .
我如何创建一个新问题
try {
const question = new questionModel({ _refExamId: req.body._refExamId, title: req.body.title });
await question.save();
return res.status(200).json({ type: "SUCCESS" });
}
catch (error) {
return res.status(500).json({
type: "ERROR",
message: "Some unknown error occurred",
});
}
【问题讨论】: