Reputation: 251
Error
Problem: Cannot read property 'length' of undefined at jade_debug.unshift.lineno (eval at (C:\Users\Dev\Node_js\node_modules\jade\lib\jade.js:160:8), :111:31) at eval (eval at (C:\Users\Dev\Node_js\node_modules\jade\lib\jade.js:160:8),
DB function
exports.selectRows = function(){
var objBD = BD();
objBD.query('SELECT * FROM usr ', function(results) {
return(results);
});
}
Route
exports.index = function(req, res) {
res.render('customer/index',{ customers: db.selectRows() });
};
index.jade
each item in customers
tr
td
a(href='/customer/details/#{item.id}') #{item.id}
td #{item.name}
td #{item.email}
td #{item.phone}
Upvotes: 1
Views: 1447
Reputation: 26849
Problem with your code is that the selectRows
method is executed asynchronously and db.selectRows()
expression in your handler method always return undefined
value and hence the execption (customers
template variable is undefined
).
You should add the following changes to your code in order to have it working correctly:
DB function :
exports.selectRows = function(callback){
var objBD = BD();
objBD.query('SELECT * FROM usr ', callback);
}
Route:
exports.index = function(req, res) {
db.selectRows(function(results){
res.render('customer/index', { customers: results });
});
}
Sometimes you may have a situation (very common Node.js pattern) where your callback
gets two parameters:
undefined
if DB query was successfulIn case of two parameters (error and results) your route should look as follows:
exports.index = function(req, res) {
db.selectRows(function(err, results){
if (err) return res.send(500, "DB QUERY ERROR");
res.render('customer/index', { customers: results });
});
}
You can also simplify your index.jade
each item in customers
tr
td: a(href='/customer/details/#{item.id}')= item.id
td= item.name
td= item.email
td= item.phone
I hope that will help.
Upvotes: 1