简体   繁体   中英

MongoDB: Cannot add to a Sub-document of a Sub-document

I am attempting to use Mongoose to add an entry to the questions array. However mongoose is saying the data I am accessing is undefined.

{"content":
    {"_id":"58c6f76e06e6edda1b000007",
     "name":"testCourse",
     "__v":0,
     "subjects": 
         [{"name":"testSubject",
           "_id":"58c6f85280a5d6591c000007",
           "questions":[]}
         ]
     }
}

Here is my method that creates the entry:

module.exports.makeQuestion = function(req, res){
    var courseid = req.params.courseid;
    var subjectid = req.params.subjectid;

    console.log("cou:"+ courseid + " sub:"+ subjectid);

    Course.findById(courseid, function(err, course){
      course.subjects.questions.push({question: req.params.question,
                                      answer:req.params.answer})
      sendJSONResponse(res, 200, course);
    });
}

What error am I making when adding the entry?

It's because course.subjects is an array. So it doesn't know which of the subdocuments you want to push the object to. To solve this you could do course.subjects.id(_id).questions.push(question) which should work if you know the ID of the subdocument-object. Else you have to loop through the array to find the one that you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM