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?

1
  • 1
    cell is the index. If you want the contents, you need to print row[cell] (and also iterate over rows[row]). Commented Dec 5, 2016 at 8:17

1 Answer 1

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>";
      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.