14

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!

Collin McGuire
  • 714
  • 3
  • 8
  • 14

1 Answers1

30

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}
c0deNinja
  • 3,956
  • 1
  • 29
  • 45
  • 1
    I forgot to include this in the sample code I gave. But when I took away JSON.stringify() on the server side it worked. – Collin McGuire Oct 09 '12 at 21:31
  • 5
    Thank Jesus, finally, I've been searching hours for that little piece of code and have even contemplating painting "JADE SUCKS" on the side of a building in goats blood. If u want another checkmark, http://stackoverflow.com/questions/20485595/how-do-i-send-on-object-from-mongodb-to-jade. THANK YOU. – Squirrl Dec 10 '13 at 04:49