【问题标题】:Jade Cannot read property 'length' of undefined in each loopJade 无法读取每个循环中未定义的属性“长度”
【发布时间】:2014-11-12 10:41:19
【问题描述】:

我的控制器中有这段代码从 mongo 检索对象并将其发送到客户端:

 index: function(req, res){
    List.find({user:req.session.user.id}).exec(function foundLists(error, foundLists) {
        if(error) {
            return res.json({error:error});
        } else {
            return res.view({ title:'Lists',lists:foundLists });
        }
    });
 }

在我看来,我会做以下事情:

extends ../layout
  block content
    .container
        p #{lists}

呈现:[object Object],[object Object]

如果我这样做p= JSON.stringify(lists)

它呈现:

[{"user":"546109c0d640523d1b838a32","name":"third","createdAt":"2014-11-11T19:39:36.966Z","updatedAt":"2014-11-11T19:39:36.966Z","id":"546265f83e856b642e3b3fed"},{"user":"546109c0d640523d1b838a32","name":"forth","createdAt":"2014-11-11T19:42:09.268Z","updatedAt":"2014-11-11T19:42:09.268Z","id":"546266913e856b642e3b3fef"}]

我正在努力实现:

#lists
    each list in lists
       p #{list}

但我收到此错误: Cannot read property 'length' of undefined

我正在使用 Sails and Jade 1.7.0

【问题讨论】:

标签: node.js pug


【解决方案1】:

你有一个对象数组,所以如果你做each list in lists 那么list 就是一个对象。我假设 Jade 想要一个字符串。如果你输入 p #{list.name} 或类似的东西应该可以工作。

如果您想显示所有内容,可以尝试嵌套循环,例如

each list in lists
    each item in list
        p #{item}

【讨论】:

    【解决方案2】:

    当列表中的至少一项不具有list 属性时,可能会发生此错误。您可以使用 if 语句来保护它:

    each val in lists
        if val.list
            each item in val
                p #{item}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多