0

I'm learning to use mysql module in node.js, so I use it with Express & Mustache to render a MySQL table and came up with this:

var express = require('express');
var app = express();

var mu2 = require('mu2');
mu2.root = __dirname + '/views';

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    port: 3306,
    database: 'breakthrough'
});

con.connect(function (err) {
    if (err) {
        console.log('Error connecting to database:\n' + err);
        return;
    }
});

app.get('*', function (req, res) {
    var tableHTML;
    function renderTable(rows) {
        tableHTML = "<table>";
        for (var row in rows) {
            tableHTML += "<tr>";
            for (var cell in row) {
                tableHTML += ("<td>" + cell + "</td>");
            }
            tableHTML += "</tr>";
        }
        tableHTML += '</table>';
    }
    con.query('SELECT * FROM drivers', function (err, rows){
        if (err) { throw(err); }
        renderTable(rows);
        htmlStream = mu2.compileAndRender('frontPage.html', {table: tableHTML});
        htmlStream.pipe(res);
    });
});

app.listen(8080, function () {
    console.log("Listening on port 8080.");
});

But the resulting table only show zeroes, one for each row:

<table>
    <tr><td>0</td></tr>
    <!-- tr repeated for each row in rows -->
</table>

Some readings suggest that iterating over objects in node.js is currently quite problematic. Is there any way I can lazy-iterate over node.js objects?

starleaf1
  • 2,701
  • 6
  • 37
  • 66
  • 1
    `cell` is the index. If you want the contents, you need to print `row[cell]` (and also iterate over `rows[row]`). – JJJ Dec 05 '16 at 08:17

1 Answers1

1

It seems that rows is an array (according to https://www.npmjs.com/package/mysql) so when you doing :

for(var row in rows)

row take only the index and not the value, that's why your second for loop is wrong. In addition take only the index and not the value

Change it to :

for (var row in rows) {
    tableHTML += "<tr>";
    for (var cell in rows[row]) {
        tableHTML += ("<td>" + rows[row][cell] + "</td>");
    }
    tableHTML += "</tr>";
}

But looping over an array using for in isn't a good idea, see Why is using "for...in" with array iteration a bad idea?

Use :

     for (var i = 0; i < rows.length; i++) {
         tableHTML += "<tr>";
         for (var cell in rows[i]) {
            tableHTML += ("<td>" + rows[i][cell] + "</td>");
         }
         tableHTML += "</tr>";
      }
Community
  • 1
  • 1
Daphoque
  • 4,421
  • 1
  • 20
  • 31