问题
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.
回答1:
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]);
回答2:
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
来源:https://stackoverflow.com/questions/20485595/how-do-i-send-on-object-from-mongodb-to-jade