Reputation: 307
I've been working on a live Q&A app in which users can create discussions, inside the discussions they can ask questions, and then add comments to the questions.
However, at the moment I'm stuck on the questions part. I can successfully create a discussion, and a question which is linked to the discussion by the discussionID (which is stored in MongoDB as an objectID(discussionID).
I'm trying to get the questions which have the same ID as the discussion, and pass them to Jade so I can loop them in divs.
My code so far is:
For the discussion controller:
function getOne(req, res, next) {
Discussion.findOne({_id: req.params.id}, function onDiscussionFound(err, discussion) {
if(!discussion) {
res.status(404).send("Discussion not found");
}
console.log(discussion);
// we return the json version with cleaned up model to the user
//res.send(discussion.toJSON());
var Questions = Question.find({discussionID: discussion.id}, function(err, data){
console.log(data);
});
//console.log(Questions);
res.render('discussion', { title: discussion.title, description: discussion.description, user: req.user, discussionID: discussion.id, questions: Questions});
});
}
So the part that I'm having issues with is:
var Questions = Question.find({discussionID: discussion.id}, function(err, data){
console.log(data);
});
The discussionID is a field in my Robomongo's collection questions, and the discussion.id is of course the ID of the discussion.
It may be a problem on my render, I'm not sure since I'm quite new to this.
In my Jade discussion.jade file I try to retrieve the questions like this:
if questions
each question in questions
p= question
But this gives me a never-ending response which looks like this:
[object Object]
[object Object]
function model(doc, fields, skipId) { if (!(this instanceof model)) { return new model(doc, fields, skipId); } Model.call(this, doc, fields, skipId); }
[object Object]
find
[object Object]
[object Object]
[object Object]
function () { var args = Array.prototype.slice.call(arguments); _this.wrap(name, fn, context, args); }
function () { var args = Array.prototype.slice.call(arguments); _this.wrap(name, fn, context, args); }
function () { var args = Array.prototype.slice.call(arguments); _this.wrap(name, fn, context, args); }
function () { var args = Array.prototype.slice.call(arguments); _this.wrap(name, fn, context, args); }
function () { var a
And so on...
My console.log of the data however returns the 3 questions that have been asked so far.
Upvotes: 2
Views: 73
Reputation: 1322
Question.find is an asynchronous call, thus you need to wait until it has executed and use the returned data aka. your Questions to render the view:
var Questions = Question.find({discussionID: discussion.id}, function(err, data){
console.log(data);
res.render('discussion', { title: discussion.title, description: discussion.description, user: req.user, discussionID: discussion.id, questions: data});
});
//console.log(Questions);
Upvotes: 2