John John - 4 months ago 22
MySQL Question

Displaying data structure instead of data

On the page it shows rows of

[object Object]
but I know there's value in it because in the console it outputs the right data. it just outputs [object Object] with no data in it when trying to display on page. If I do console.log then it shows the correct data. It seems like the HTML page renders the row data structure and not the data itself.

Below is the route page

var express = require('express');
var router = express.Router();
var mysql = require('mysql');


/* GET home page */
router.get('/', function(req, res, next) {
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});

connection.connect();

connection.query('SELECT hashtag from recipients', function(err, rows, fields) {
if (!err) {
console.log(rows);
//send rows to template engine to render HTML.
res.render('mysql', {
rows: rows,
title:''
});
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});

// Important
module.exports = router;


Below is the view page

<html>

<head>
<title> <%= title %></title>
</head>

<body>
<table>
<tr>some heading</tr>
<% for(var i=0; i< rows.length; i++) { %>
<tr>
<td>
<%= rows[i] %>
</td>
</tr>
<% } %>

</table>
</body>

</html>

Answer

"[object Object]" is result of converting your object to string. The conversion is likely performed automatically inside your template. Just change the part where you interpolate data from object to object string property.

For example

  res.render('mysql', {
    rows: rows,
    fields: fields,
    title:''
  });

And view:

<html>

<head>
  <title> <%= title %></title>
</head>

<body>
  <table>
    <tr>some heading</tr>
    <% for(var i=0; i< rows.length; i++) { %>
      <tr>
        <% for(var f=0; f< fields.length; f++) { %>
        <td>
          <%= rows[i][fields[f].name] %>
        </td>
        <% } %>
      </tr>
      <% } %>

  </table>
</body>

</html>

The reason console.log is printing content of your object is that it looks at the type of parameter and does various smart tricks to print content nicely via util.inspect (look at all format* functions below inspect)