【发布时间】:2021-04-10 12:49:39
【问题描述】:
我正在开发一个 nodejs 项目,其中 MongoDB 用于数据库存储,EJS 用于模板。
我遇到了一个问题,即对象数组没有正确传递给 EJS。该代码在 forums.js 中按预期工作(并且从 console.log 中按预期输出),但在 forums.ejs 中无法正常工作。加载项目时,我收到一个错误:“无法读取未定义的每个属性”。
有人可以帮我吗?谢谢!
forums.js
var allCategories = await dbo.getForumCategories();
allCategories.forEach(async function(category) {
category.forumArray = await dbo.getForums({categoryId: new ObjectID(category._id)});
console.log(category.forumArray); //works fine, displays as intended
});
res.render('forums.ejs', { categories: allCategories, user: req.user });
forums.ejs
<% categories.forEach(function(category) { %>
//this part works
//some code
<% category.forumArray.forEach(function(forum) { %>
//this is not working
//Can not read property forEach of undefined
<% }); %>
<% }); %>
【问题讨论】: