zoomer
zoomer

Reputation: 87

Passing variable from app.get to pug view

I have the below code that make a call to my database and pulls down info

    // GET the number of apples left in stock
    app.get('/apples', function (req, res) {
        sql.connect(config, function() {
            var request = new sql.Request();
            request.query("select quantity from table WHERE type = 'apple'", function(err, recordset) {
        var arrayLength = recordset.length;
        for (var i = 0; i < arrayLength; i++) {
        console.log(recordset[i]["quantity"]);
res.render('index', {results: recordset});
        };
    });
})
})

this works perfectly .. when I browse to that it sends me to the index page and then I can see the values from the database spit out in my console log.

In my index.pug I then have this:

h3(align='middle') #{results}

On the index page I just see this [object Object]

Upvotes: 1

Views: 3067

Answers (1)

agit
agit

Reputation: 631

First off all you shouldn't call res.render multiple times in the for loop.

app.get('/apples', function (req, res) {

  sql.connect(config, function () {

    var request = new sql.Request();
    request.query("select quantity from table WHERE type = 'apple'", function (err, recordset) {
      var arrayLength = recordset.length;
      for (var i = 0; i < arrayLength; i++) {
        console.log(recordset[i]["quantity"]);
      };
      res.render('index', { results: recordset });
    });
  });
});

Then you should use each in your pug file to iterate resultset. More doc for iteration : https://pugjs.org/language/iteration.html

each val in results
  h3(align='middle')=val.quantity

Upvotes: 3

Related Questions