0

I have two collections questions and answers which look like this.

question:

{ 
"_id" : ObjectId("56a450880c9a072eb092774f"), 
"text" : "Who are you?"
}

answer:

{ 
"_id" : ObjectId("56a452930c9a072eb092775f"), 
"text" : "I'm me!", 
"correct" : true, 
"question_id" : ObjectId("56a450880c9a072eb092774f")
}

and then I have two Schemas :

AnswerSchema:

var answerSchema = new Schema({
answer: String,
correct: Boolean,
question_id : {type: db.Schema.Types.ObjectId, ref: 'Question'}
});

QuestionSchema

var  questionSchema = new Schema({
text: String,
answers : [answerSchema]
});

So basically, I want to query the data base to spit a json like this where the answers get populated:

{
_id: "56a451150c9a072eb0927751",
text: "Who are you?",
answers: [
  { "answer" : "I'm me!", "correct": true },
  { "answer" : "I'm you!", "correct": false },
  { "answer" : "You are you", "correct": false }
]}

I can query the questions but the answers are not populated by doing this:

    Question.find({})
    .populate("answers")
    .exec(function (err, questions) {
        //if(err) res.status(500).send(err);
        //else res.json(questions);
        res.json(questions);
});

How can I achieve what I'm trying to do. Thanks.

0

1 Answer 1

1

Since the answerSchema is the sub-document of QuestionSchema

var questionSchema = new Schema({
   text: String,
   answers : [answerSchema]
});

To meet your requirement, it is easy to do with

Question.find({})
    .exec(function (err, questions) {
        // all answers are in the every question as sub-document.
});

As for populate, when you want to

Question.find({})
  .populate("answers")
  .exec(function (err, questions) {
     //....
});

The questionSchema and answerSchema should be

var answerSchema = new Schema({
  answer: String,
  correct: Boolean
});
var Answer = mongoose.model("Answer", answerSchema);

var questionSchema = new Schema({
  text: String,
  answers : [{type: db.Schema.Types.ObjectId, ref: 'Answer'}]
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.