Rendering json Object with express and jade - Can't access json fields
15,258
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}
Related videos on Youtube
Comments
-
NorRen almost 2 years
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?
-
c.P.u1Brother, if
result
is a single-document array, shouldn't you be usingresult[0].name
,result[0].unitprice
? What doesconsole.log
print?
-
-
NorRen almost 11 yearsEven if the question has been answered before by c.P.u, your answer is correct ;)
-
Amaranadh Meda over 9 yearsHey how to access the product in the client side javascript ?