Reputation: 721
Relevant Express part of my node application:
/*Route to Product Views*/
app.get('/product/:id', function(req, res){
Product.find({_id: req.params.id}, function (error, data) {
if(error){
console.log(error);
} else {
console.log("DATA :" + data); //correct json object
res.render('product',{
title: 'Product Template',
result: data
}
);
}
});
});
Jade Template:
!!! 5
html
head
title #{title}
body
h1 #{result.name}
h2 #{result.unitprice}
p.
#{result.description}
h3 #{result}
So if I vistit http://myhost.com/product/51fa8402803244fb12000001 all I see is the output of h3 #{result}, which is:
[{
__v: 0,
_id: 51fa8402803244fb12000001,
description: 'Awesome stuff you really need',
discontinued: false,
name: 'Some product',
unitprice: 5.99
}]
Using JSON.stringify makes no difference except that h3 #{result} returns "stringified" JSON. How to correctly access the fields of the json string?
Upvotes: 3
Views: 15318
Reputation: 727
The output of your DB query returns the result as an array, so you need to send as data[0] to the product template, so that you can access directly the values else you need to access as result[0].name etc.
/*Route to Product Views*/
app.get('/product/:id', function(req, res){
Product.find({_id: req.params.id}, function (error, data) {
if(error){
console.log(error);
} else {
console.log("DATA :" + data[0]); //correct json object
res.render('product',{
title: 'Product Template',
result: data[0]
}
);
}
});
})
Jade Template:
!!! 5
html
head
title #{title}
body
- product = typeof(result) != 'undefined' ? result : { }
h1 #{product.name}
h2 #{product.unitprice}
p.
#{product.description}
h3 #{product}
Upvotes: 5