B
B
BEKa T2020-01-03 20:53:26
Node.js
BEKa T, 2020-01-03 20:53:26

How to iterate mysql array?

Can't iterate over array with EJS template engine. Gives [object Object]
index.ejs

<h1>
    <% for (var i = 0; i < sms.length; i++) { %>
            <p><%= sms[i].text %></p>
        <% } %>
  </h1>


app.js

var reqDB = 'SELECT * FROM messages';
var sms = db.query(reqDB, (err, result) => {
  if (err) throw err;
  console.log(result);
});

// Chat
app.get('/chat', function (req, res) {
  res.render('chat', {
    sms
  })
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Shohruh Shaimardonov, 2020-01-03
@joeberetta

It's not about the template engine, but about the request, which does not write the result of the request to the database in the sms variable. You can check through the logs in the console.
Here is the solution to your problem

A
abberati, 2020-01-03
@abberati

The template engine calls .toString() on whatever you output. For objects, this method returns exactly what you see. Use JSON.stringify() , see what you actually output. Well, or use a debugger, if you know how.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question