Jade Cannot read property 'length' of undefined in each loop
Asked Answered
Q

2

7

I have this code in my controller retrieving an object from mongo and sending it to the client:

 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 });
        }
    });
 }

In my view I do the following:

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

Which renders:[object Object],[object Object]

If I do p= JSON.stringify(lists)

It renders:

[{"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"}]

I'm trying to achieve:

#lists
    each list in lists
       p #{list}

But I get this error: Cannot read property 'length' of undefined

I'm using Sails and Jade 1.7.0

Quevedo answered 12/11, 2014 at 10:41 Comment(1)
Driving me crazy too :( What did you see?Anhwei
E
1

You have an array of objects, so if you do each list in lists then list is an object. I assume Jade wants a string. If you put p #{list.name} or something similar that should work.

If you want to show everything you can try nesting your loops like

each list in lists
    each item in list
        p #{item}
Eddie answered 3/4, 2015 at 23:12 Comment(0)
C
0

This error can occurred when at least one of the items in the lists does not have a list property. You can protect this using an if statement:

each val in lists
    if val.list
        each item in val
            p #{item}
Countervail answered 26/11, 2018 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.