在Mongoose与Express中如何关联Question模型获取QuestionText字段
问题原因
你在查询Survey集合时没有填充关联的Questions字段,Mongoose默认不会自动加载ref关联的集合数据,所以你拿到的SurveyList[count].Questions只是一个ObjectId类型的值,不是完整的Question文档,自然无法读取QuestionText属性。
修复方案
使用Mongoose内置的populate方法即可完成关联字段的自动填充,不需要手动嵌套调用Question查询,实现更简洁高效。
1. 修改控制器查询逻辑
在Survey.find后链式调用populate方法,指定要填充的关联字段:
module.exports.displayLiveSurveys = (req, res, next) => { Survey.find() .populate('Questions') // 新增这行代码,填充关联的Question完整数据 .exec((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, }); } }); };
2. 修改前端模板代码
填充完成后SurveyList[count].Questions就会变成完整的Question文档,直接读取对应属性即可,可添加可选链判断避免关联字段为空时报错:
<!-- 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?.QuestionText || '' %></td> <% } %>
内容的提问来源于stack exchange,提问作者koda
相关产品推荐
相关产品推荐

