【问题标题】:Array not being passed to EJS数组未传递给 EJS
【发布时间】: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

<% }); %>
<% }); %>

【问题讨论】:

    标签: node.js ejs


    【解决方案1】:

    这是因为您的 render 函数在您的 forEach 完成运行之前被调用。

    请看下面的例子:

    const foo = [1, 2, 3];
    
    foo.forEach(async function(bar) {
        bar = await mockCall() + bar;
    })
    
    console.log(foo) //> [ 1, 2, 3 ]
    console.log("Are methods here running?") //> Logs correctly and demonstrates any function here would run before the `foo.forEach` is done running.
    
    function mockCall() {
        return new Promise((res, rej) => {
            setTimeout(() => {
                res('From the promise: ');
            }, 500)
        })
    }
    

    【讨论】:

    • 谢谢。如何在我的示例中解决此问题?
    【解决方案2】:

    在您的 res.render 中,您将类别作为 allCategories 传递,但我看不到 ejs 文件中的类别是在哪里定义的。

    【讨论】:

    • 对不起我的错 - 找到了 :)
    【解决方案3】:

    我已通过将 for each 循环替换为 for 循环来修复我的代码,如下所示:

    for (const category of allCategories) {
        category.forumArray = await dbo.getForums({categoryId: new ObjectID(category._id)});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 2018-04-09
      • 1970-01-01
      • 2014-06-30
      • 2016-03-04
      • 2014-08-26
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多