Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

node.js - Using Jade to iterate JSON

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...