Rodney Wilson
Rodney Wilson

Reputation: 369

How to iterate and parse JSON from query in Express/Jade?

I am new to nodejs so I'm thinking this is simple but I cannot find a way to pass the JSON data from a select query to the Jade view. I am using Node.js Tools for Visual Studio to create the project which uses Express + Jade. Here is my index.js file:

exports.products = function (req, res) {
var request = new sql.Request(connection);
console.log("Connection successful.");
request.query('SELECT * FROM product', function (err, data) {
    console.log(data[i]);
    res.render('products', {
        title: 'Products', 
        year: new Date().getFullYear(), 
        message: 'Products page with all devices',
        name: 'Rodney',
        result: data[i]
    });    
});

This the view I'm using in Jade to render the results:

- product = typeof(result) != 'undefined' ? result : { }
for p in product
  h3 #{product.Name}

I am getting the error i is not defined which makes sense, but I can only show 1 record if I change it to result: data[0]. Here is a sample of how the JSON is structured: { Id: 56, Name: 'Motion', ModelString: '1234-G', Description: 'Motion Front Door', Released: true, BoardId: 29, CreateDate: Wed Aug 05 2015 06:29:31 GMT-0500 (Central Daylight Time), SerialNumberCode: 'AAA', ExtensionId: 9, SKU: '1234-G', CurrentTest: false, ModelEncodingNumber: -1 }

How can I show all records with the column name?

Upvotes: 3

Views: 225

Answers (2)

xaviert
xaviert

Reputation: 5942

You can actually directly forward the data to your res.render method like this:

res.render('products', {
    ...
    products: data
});

// in view.jade
for p in product
    h3 #{product.Name}

If you only need the names of your product, you can loop over your data first, collect the names and store them in another list:

var allNames = data.map(function(element) {
    return element.Name;
})

res.render('products', {
    ...
    names: allNames
});  

// view.jade
for name in names
    h3 #{name}

Upvotes: 1

jkris
jkris

Reputation: 6561

Have you tried just passing data?

EDIT:

Hope this works

- productList = typeof(result) != 'undefined' ? 
result : { }
for product in productList
  for p in product
    h3 #{p.Name}

Upvotes: 0

Related Questions