node.js 使用 Jade 迭代 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12794078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:26:26  来源:igfitidea点击:

Using Jade to iterate JSON

jsonnode.jsmongodbexpresspug

提问by Collin McGuire

I am trying to iterate a JSON doc using JADE.

我正在尝试使用 JADE 迭代 JSON 文档。

my server(running node.js + express) is doing the following on a .get() request,

我的服务器(运行 node.js + express)正在对 .get() 请求执行以下操作,

app.get('/search/', function(req,res){

  // Parse the query
  var dbQuery = url.parse(req.url, true).query;
  var product = dbQuery.product;
  var category = dbQuery.category;
  console.log('Searching for: ' + product + ' in ' + category);

  //Mongo DB setup then query
  var result;
  var server = new mongodb.Server('23.23.129.158', 27017, {});
  new mongodb.Db('militaryListDB', server, {}).open(function(err, client){
    if(err) throw err;

    var collection = new mongodb.Collection(client, 'products');
    collection.find({}).toArray(function(err, results){
      console.log(results);
      console.log(JSON.stringify(results));
      res.render('results', {result: JSON.stringify(results), title: 'Test'});
    });
  });
});

and this is what it is rendering to the client.

这就是它呈现给客户端的内容。

[{"_id":"50738ebbe3d87c6beaddb6f2","name":"tv","category":"tech","cost":"30"}]

I have read over the jade documentation for iterating an array and I thought it would be the same for JSON, but it isn't working. It is just displaying a blank space. When I try this,

我已经阅读了用于迭代数组的 jade 文档,我认为它与 JSON 相同,但它不起作用。它只是显示一个空白区域。当我尝试这个时,

extends layout
block content
  div#wrapper                 
    p #{results}

it will display the JSON doc. But when I try this,

它将显示 JSON 文档。但是当我尝试这个时,

extends layout
block content
  div#wrapper                 
    p #{results.name}

and it displays a blank space. When it should be displaying is "tv". If someone could help me understand iterating JSON docs that would be awesome.

它显示一个空格。什么时候应该显示是“电视”。如果有人能帮助我理解迭代 JSON 文档,那就太棒了。

Thank you!

谢谢!

回答by c0deNinja

In your code you are not iterating through the resultsarray, do to so you should do something like this:

在你的代码中,你没有遍历results数组,这样做你应该做这样的事情:

for result in results
     p #{result.name}