如何用Mongoose、Express在同一页面展示两个MongoDB文档数据
解决Mongoose关联数据在EJS页面展示的问题
1. 修复模型导出错误
你的代码最后两行导出语句会导致Timer被覆盖,最终仅导出Customer。修改导出方式,同时导出两个模型:
// 替换原有的两行module.exports语句 module.exports = { Customer, Timer };
2. 修改路由,同时获取Customer和关联的Timer数据
在/customers/:id路由中,需要查询当前Customer对应的所有Timer记录(Timer的customer字段存储了Customer的ObjectId)。使用Promise.all并行执行两个查询,提升效率:
router.get('/customers/:id', (req, res) => { const id = req.params.id; Promise.all([ // 查询指定Customer Customer.findById(id), // 查询该Customer下的所有Timer Timer.find({ customer: id }) ]) .then(([customer, timers]) => { // 将customer和timers数据传递给EJS模板 res.render('details', { customer, timers, title: 'Customer Details' }); }) .catch(err => { console.error(err); res.status(500).send('获取数据失败'); }); });
3. 更新EJS模板,渲染Timer数据
模板中需要遍历timers数组展示每个Timer的信息,同时处理无Timer记录的情况:
<div class="container"> <div> <h2><%= customer.firstName %></h2> </div> <div>Email: <%= customer.email %></div> <!-- 展示关联的Timer列表 --> <div class="timers-section"> <h3>关联计时器</h3> <% if (timers.length > 0) { %> <% timers.forEach(timer => { %> <div class="timer-item"> <p><strong>摘要:</strong> <%= timer.summary %></p> <p><strong>详情:</strong> <%= timer.detailed %></p> <p><strong>创建时间:</strong> <%= timer.createdAt.toLocaleString() %></p> </div> <% }) %> <% } else { %> <p>暂无关联的计时器记录</p> <% } %> </div> </div>
补充说明
- 如果需要从Customer模型直接关联查询Timer,可以在
custDataSchema中添加反向引用字段(如timers: [{ type: Schema.Types.ObjectId, ref: 'Timer' }]),但需要在创建Timer时同步更新Customer的timers数组。当前直接查询Timer的方式更简洁,适配你的需求。 - 所有实现均使用原生JavaScript,未引入jQuery,符合你的要求。
内容的提问来源于stack exchange,提问作者Div
相关产品推荐
相关产品推荐

