2

I'm trying to access an object that I retrieve from MongoDB with my client-side JS. Specifically, I want to be able to loop through and use the arrays within the object. Here is my server-side JS which successfully finds the results and logs them to terminal.

app.get("/post/:id", function (req, res, next) {
  var id = req.param('id');
  var query = BlogPost.findById(id).populate('author');

  BlogPost.find(query, {"answers":"true", "blanks":"true", "_id":0}, function(err, results){

  console.log('Results '+results);//This prints an object like:// { answers: [ 'more', 'One', 'more' ], blanks: ['try']}

  query.exec(function (err, post) {
    if (err) return next(err);
    if (!post) return next(); // 404

    res.render('post/view.jade', { post: post, results: results });
  })
})
})

And my jade:

  #luck
   #{results}

And then my client-side JS:

var results = $('#luck').html();
console.log(results.answers[2]);

I get undefined with the console.log and the results are printed on the page.

Squirrl
  • 4,909
  • 9
  • 47
  • 85

2 Answers2

3

If the results are printed on the screen but you cannot traverse the object, then it may mean a few things:

1) The object might be an array i.e. results[0].whatever instead of results.whatever

2) The object is in string form and you need to call JSON.parse(results) before you can traverse it

var results = JSON.parse($('#luck').html());
console.log(results.answers[2]);
Xinzz
  • 2,242
  • 1
  • 13
  • 26
3

Thanks for the answer @Xinzz, but this jade:

for result in results
     p #{result.answers}

ended up working for me. From here: Using Jade to iterate JSON

Community
  • 1
  • 1
Squirrl
  • 4,909
  • 9
  • 47
  • 85