Nor*_*Ren 2 json node.js express pug
我的节点应用程序的相关Express部分:
/*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
}
);
}
});
});
Run Code Online (Sandbox Code Playgroud)
玉模板:
!!! 5
html
head
title #{title}
body
h1 #{result.name}
h2 #{result.unitprice}
p.
#{result.description}
h3 #{result}
Run Code Online (Sandbox Code Playgroud)
所以如果我vistit http://myhost.com/product/51fa8402803244fb12000001,我看到的是h3#{result}的输出,它是:
[{
__v: 0,
_id: 51fa8402803244fb12000001,
description: 'Awesome stuff you really need',
discontinued: false,
name: 'Some product',
unitprice: 5.99
}]
Run Code Online (Sandbox Code Playgroud)
使用JSON.stringify没有区别,除了h3#{result}返回"stringified"JSON.如何正确访问json字符串的字段?
数据库查询的输出将结果作为数组返回,因此您需要将data [0]作为数据发送到产品模板,以便您可以直接访问您需要访问的其他值[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]
}
);
}
});
})
Run Code Online (Sandbox Code Playgroud)
玉模板:
!!! 5
html
head
title #{title}
body
- product = typeof(result) != 'undefined' ? result : { }
h1 #{product.name}
h2 #{product.unitprice}
p.
#{product.description}
h3 #{product}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14508 次 |
| 最近记录: |