I'm getting started in Node.js and I'm completely confused as to why I can't get the results of my SQL query to render on a page.
connection.query('SELECT * FROM testTable', function selectCb(err, rows, fields) {
if (err) {
throw err;
}
for (var i in rows) {
console.log(rows[i]);
}
res.render('showResults.jade', {
results: rows
});
});
The results display perfectly in the console, but when I try to render them with Jade I get a number of bullet points (equal to the number of entries in the table), but with each one followed by [object, Object]. This is my Jade file:
h1 SQL Results are as follows:
ul
each item, i in results
li= item
Is there an extra step or something that I need to get the results to display properly?
The output you're seeing is because Jade is simply calling .toString() on the result of the expression. And, for Objects like item, that's the default result:
> {}.toString()
'[object Object]'
To get something more useful, you'll have to specify the format:
li #{item.prop1} (#{item.prop2})
For JSON:
li= JSON.stringify(item)
If you want the format you see with console.log(), you can expose the function it uses, util.inspect(), as a view helper:
// Express 3
app.locals.inspect = require('util').inspect;
li= inspect(item)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With