Using Jade to iterate JSON

2019-01-24 03:06发布

问题:

I am trying to iterate a JSON doc using JADE.

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

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,

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

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

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.

Thank you!

回答1:

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

for result in results
     p #{result.name}