How to iterate through an array of mysql?

Not fails to sort the array by the template engine EJS. Gives [object Object]

index.ejs
the <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
})
});
April 4th 20 at 00:41
2 answers
April 4th 20 at 00:43
It is not in the template, and the query that into a variable sms will not write the result of the query in the database. You can check through the logs in the console.
There is the solution for your problem
And in the console all shows well

[
 RowDataPacket { id: 1, text: 'g' },
 RowDataPacket { id: 2, text: 'rt' },
 RowDataPacket { id: 3, text: 'Hi' },
 RowDataPacket { id: 4, text: 'Hello' }
]
- crystel_Glover3 commented on April 4th 20 at 00:46
@crystel_Glover3, then the problem is that it's not just an object.
Do this:
const parsedSMS = JSON.parse(JSON.stringify(sms)); - urban50 commented on April 4th 20 at 00:49
@urban50,

const parsedSMS = JSON.parse(JSON.stringify(sms));
^

TypeError: Converting circular structure to JSON
 --> starting at object with constructor 'Query'
 | property '_timer' -> object constructor with the "Timer"
 --- property '_object' closes the circle
 at JSON.stringify (<anonymous>)
 at Object.<anonymous> (/home/bred/codes/ToDo149/app.js:48:35)
 at Module._compile (internal/modules/cjs/loader.js:959:30)
 at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
 at Module.load (internal/modules/cjs/loader.js:815:32)
 at Function.Module._load (internal/modules/cjs/loader.js:727:14)
 at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
 at internal/main/run_main_module.js:17:11
- crystel_Glover3 commented on April 4th 20 at 00:52
April 4th 20 at 00:45
The template engine calls .toString() what you get. Objects this method returns what you see. Use JSON.stringify(), see what you actually get. Or use debugger if you can.
Yes, actually that's not the point, he's got sms in fact lies in the result, which he catches through the console.log and sms it assigns some kind of game - Alexandrine_Cormier8 commented on April 4th 20 at 00:48
@Alexandrine_Cormier8, all done

app.js

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

 for(let i=0; i < result.length; i++){
 var smsText = result[i].text;
console.log(smsText);
}
});


bash

MySQL CONNECT...
[
 RowDataPacket { id: 1, text: 'g' },
 RowDataPacket { id: 2, text: 'rt' },
 RowDataPacket { id: 3, text: 'Hi' },
 RowDataPacket { id: 4, text: 'Hello' },
 RowDataPacket { id: 5, text: 'Hello everybody!' },
 RowDataPacket { id: 6, text: 'Hello!' }
]
g
rt
Hi
Hello
Hi all!
Hi!
- crystel_Glover3 commented on April 4th 20 at 00:51

Find more questions by tags Node.js