0

I am trying to run a select query from db and print results. But even i see result in console i don't see in index page. (Hovewer i see result in console but it is also doesn't show correctly. I have 2 rows in db but i see 3 lines for each row. So result in console is : 2X3=6 rows.) I put screenshot about console result end of the question.

Code in app.js

app.use('/', routes, function(req, res){
    pg.connect(connect, function(err, client, done){
    if(err){
      return console.error('errrr', err)
    }
    client.query('select * from recipes', function(err, result){
    if(err){
      return console.error('error running query', err);
    }
     console.log(result.rows);
     res.render('index.njk', { recipes: result.rows});
     done(); 
    });
    }); 
    });

Code in index.njk

<ul>
  {% for name, item in recipes %}
  <li>{{ name }}: {{ item.name }}</li>
  {% endfor %}
</ul>

this is result of the console Can you please help me to fix it?

Can Aslan
  • 53
  • 2
  • 11

2 Answers2

0

It seems like (via your picture of the console) that result.rows is an array of arrays that has 2 values in it. Therefore, while looping over the value in your index.njk, recipes is an array of arrays and doesn't contain an item that has a name attribute.

If you set recipes: result.rows[0] that should provide a quick fix:

res.render('index.njk', { recipes: result.rows[0]});

This allows you to get the first element in your array of arrays, which is okay, because the array held within only has 1 element (the 2 items you actually want!). You should check before you do this that result.rows.length > 0 so you don't go out of bounds and get an error.

if(result.rows.length > 0) {
  res.render('index.njk', { recipes: result.rows[0]});
}else {
  console.log('No rows found in DB');
}
lplatz
  • 101
  • 7
0

I have solved my issue by using below code block in index.js instead of using app.js. I am not sure it is correct way but it is working fine now. If it is not correct way, let me correct it please.

router.get('/', function(req, res){
  pg.connect(connect, function(err, client, done){
   if(err){
    return console.error('errrr', err)
    }
   client.query('select * from recipes', function(err, result){

    if(err){
      return console.error('error running query', err);
     }
    if(result.rows.length > 0) {
        res.render('index.njk', { recordResult: result.rows});
       console.log(result.rows);
     }else {
        console.log('No rows found in DB');
      }
    done() 
    });
  }); 
});
Can Aslan
  • 53
  • 2
  • 11