使用express和jade渲染json对象 - 无法访问json字段

3

我的Node应用程序中相关的表达部分:

/*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模板:

!!! 5
html
  head
    title #{title}
  body
    h1 #{result.name}
    h2 #{result.unitprice}
    p.
       #{result.description}
    h3 #{result}

因此,如果我访问http://myhost.com/product/51fa8402803244fb12000001,我只会看到

#{result}

的输出结果。

[{ 
__v: 0, 
_id: 51fa8402803244fb12000001, 
description: 'Awesome stuff you really need', 
discontinued: false, 
name: 'Some product', 
unitprice: 5.99 
}]

使用JSON.stringify没有什么不同,只是h3 #{result}返回“字符串化”的JSON。 如何正确地访问json字符串的字段?


2
兄弟,如果result是一个单文档数组,你不应该使用result[0].nameresult[0].unitprice吗?console.log打印了什么? - c.P.u1
谢谢兄弟,如果没有使用JSON.stringify(),它就像这样工作! - NorRen
1个回答

5
您的DB查询的输出结果是一个数组,因此您需要将其发送为data[0]到产品模板,这样您就可以直接访问值,否则您需要访问result[0].name等内容。
/*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模板:

!!! 5
html
  head
    title #{title}
  body
    - product = typeof(result) != 'undefined' ? result : { }
    h1 #{product.name}
    h2 #{product.unitprice}
    p.
       #{product.description}
    h3 #{product}

即使问题之前已经被c.P.u回答过,你的答案也是正确的 ;) - NorRen
嘿,如何在客户端JavaScript中访问产品? - Amaranadh Meda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接