I want to pass a list of objects from my database to the pug view, but I got the Error at the bottom of the post. Here is the code of what I try:
app.js Here is the function to get the objects and put them into a list. Thers also the route with the function call to get the list.
//...
function getEntryList(db) {
connection.query(connection.format('SELECT name FROM ??', [db]), (err, result, fields) => {
if (err || !result) {
utils.log(`[MySQL] ${err}`);
return Array();
}
list = Array();
Object.keys(result).forEach(key => {
row = result[key];
entry = {title: row.name, url: `/${db}/${row.id}`};
list.push(entry);
});
return list;
});
}
//...
app.get('/employees', localSession, (req, res) => {
list = getEntryList('employees');
res.render('employees', {title: 'Employees', list: list});
});
//...
content_with_list.pug This view is where the error happens.
extends layout
block content
.content-info
block content_info
.content-list.navigation
nav
ul
each entry in list
li
a(href=entry.url)= entry.title
else
li No employees found!
employees.pug This view extends from the view with the error.
extends content_with_list
block content_info
if result
table
tr
td(rowspan='7' style='vertical-align: top;')
div
img(src="#{result.image}")
p Level
span(style={color: secLevel.color})= secLevel.secName
td Name:
td
tr
td MC-Username:
td
tr
td Address:
td
tr
td Nationality:
td
tr
td Species:
td
tr
td Gender:
td
tr
td Job:
td
tr
td
td Projects:
td
I get this error:
TypeError: project\views\content_with_list.pug:9
7| nav
8| ul
> 9| each entry in list
10| li
11| a(href=entry.url)= entry.title
12| else
Cannot read property 'length' of undefined
at eval (eval at wrap (project\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:163:32)
at eval (eval at wrap (project\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:203:4)
at template (eval at wrap (project\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:295:7)
at Object.exports.renderFile (project\node_modules\pug\lib\index.js:454:38)
at Object.exports.renderFile (project\node_modules\pug\lib\index.js:444:21)
at View.exports.__express [as engine] (project\node_modules\pug\lib\index.js:493:11)
at View.render (project\node_modules\express\lib\view.js:135:8)
at tryRender (project\node_modules\express\lib\application.js:640:10)
at Function.render (project\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (project\node_modules\express\lib\response.js:1012:7)