Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting [object Object] when I try to display SQL query results in Jade

Tags:

node.js

pug

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?

like image 500
karoma Avatar asked Feb 18 '23 12:02

karoma


1 Answers

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)
like image 68
Jonathan Lonowski Avatar answered Mar 02 '23 01:03

Jonathan Lonowski