简体   繁体   English

MongoDB:无法添加到子文档的子文档

[英]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. 这是因为course.subjects是一个数组。 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. 为了解决这个问题,您可以执行course.subjects.id(_id).questions.push(question) ,如果您知道子文档对象的ID,该代码应该可以工作。 Else you have to loop through the array to find the one that you're looking for. 否则,您必须遍历数组以查找所需的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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