【发布时间】:2021-07-25 07:07:36
【问题描述】:
我想引用调查模型中引用的我的问题模型文本。我可以得到问题的 ID,但如果我写,我就无法得到 QuestionText
SurveyList[count].Questions.QuestionText
这行得通:
SurveyList[count].Questions._id
前端的完整代码:
<!-- All Surveys -->
<% for (let count = 0; count < SurveyList.length; count++) { %>
<tr>
<!-- Display title -->
<td class="text-center text-white"><%= SurveyList[count].Title %></td>
<!-- Display type -->
<td class="text-center text-white"><%= SurveyList[count].Type %></td>
<td class="text-center text-white"><%= SurveyList[count].Questions._id %></td>
<% } %>
我的问题模型架构:
// create a question model
let questionModel = mongoose.Schema(
{
QuestionText: String,
Options: String,
},
{
collection: "questions",
}
);
我的调查模型架构:
let surveyModel = mongoose.Schema(
{
Title: String,
Type: [String],
Questions: { type: mongoose.Schema.Types.ObjectId, ref: "questions" },
Answered: { type: Number, default: 0 }, // how many times users answered
DateCreated: { type: Date, default: Date.now }, // date created
Lifetime: { type: Date, default: Date.now }, // Survey expiry
},
{
collection: "surveys",
}
);
控制器:
module.exports.displayLiveSurveys = (req, res, next) => {
Survey.find((err, surveyList) => {
if (err) {
return console.error(err);
} else {
res.render("content/survey/live-surveys", {
title: "Live Surveys",
page: "live-surveys",
username: req.user ? req.user.username : "",
SurveyList: surveyList,
});
}
});
};
如果有一种方法可以在 Survey.find 中引用 Question.find 并将 QuestionList 添加到 res.render 也可能有效?我试过了,没有运气。
调查负载:
{
"_id": {
"$oid": "60fd0c7ecd479a846f1f0fe5"
},
"Type": ["TF"],
"Answered": {
"$numberInt": "0"
},
"Title": "hello",
"Questions": {
"$oid": "60fd067d736566143839e3fd"
},
"DateCreated": {
"$date": {
"$numberLong": "1627195005136"
}
},
"Lifetime": {
"$date": {
"$numberLong": "1627195005136"
}
},
"__v": {
"$numberInt": "0"
}
}
问题负载:
{
"_id": {
"$oid": "60fd0cbacd479a846f1f0fe6"
},
"QuestionText": "test",
"Options": "tester",
"__v": {
"$numberInt": "0"
}
}
【问题讨论】:
标签: javascript mongodb express mongoose