Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Rendering json Object with express and jade - Can't access json fields

Rendering json Object with express and jade - Can't access json fields

Problem

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?

Problem courtesy of: NorRen

Solution

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}
Solution courtesy of: Jeet

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Rendering json Object with express and jade - Can't access json fields

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×