Lukasz Migut Lukasz Migut - 1 year ago 120
MySQL Question

ejs templating engine with express 4, foreach fuction for object don't work

I use ejs 1.0 and express 4 and i have problem with iteration. I try to use forEach for my object returned from database (mysql). This is my code for express:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var path = require('path');
var db = require('./config/db.js');

app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'src')));

var router = express.Router();

.post(function(req, res, next){
db.query('INSERT INTO task SET todo_title = ?, todo_description =?',[req.body.title, req.body.description], function(err, info){
if(err) {
console.log('db error', err);
console.log('zadanie dodano z id: ');

}).get(function(req, res, next){
db.query('SELECT todo_id, todo_description, data FROM task', function(err, result){
if(err) throw err;
var data = JSON.stringify(result);
res.render('pages/index', {items: data});

.get(function(req, res){

}).post(function(req, res){

}).delete(function(req, res){

app.use('/api', router);

and template:

<!DOCTYPE html>
<% include ../partials/header %>
<body class="container">
<section id="main">
<% items.forEach(function(item) { %>
<li><% item.todo_id %></li>
<% }); %>
<form action="/api/todo" method="POST">
<label for="title">Nazwa zadania</lablel><br>
<input name="title" type="text"><br>
<label for="description">Opis zadania</label><br>
<textarea name="description"></textarea><br>
<% include ../partials/footer %>

I try also for() but its don't work to. My object returned from get route:


Answer Source

The issue is likely with the use of stringify():

db.query('SELECT todo_id, todo_description, data FROM task', function(err, result){
    // ...
    var data = JSON.stringify(result);
    res.render('pages/index', {items: data});

String values, as stringify() creates, don't have a .forEach() method. And, res.render() and EJS don't require values to be JSON-encoded.

You can just assign result, an Array of Objects, to items without involving JSON:

res.render('pages/index', { items: result });

Or, you would need to parse() it within the view:

<% JSON.parse(items).forEach(function(item) { %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download