1

I want to update a subdocument's value and after that save the main document. So the changes to the subdocument gets saved to the database. Here is my code ATM, I find the correct subdocument, that is not the problem I guess. But it doesn't save the changes.

 projectModel.findById({_id: req.body.projectId})
  .then(function(doc){

    question = doc.qp.questions.filter(q => {return q._id == req.body.questionId})[0];

    var ans = question.answers.filter(a => {return a._id == req.body.answerId})[0];
    if(ans)
    {console.log(ans)}
    ans.value = req.body.answerValue;

    doc.save().then(res.send({questionId: req.body.questionId,answerId: req.body.answerId,answerValue: req.body.answerValue}))

  })
  .catch(error => console.log(error))

my object is kinda complex, and it has to be.. it looks something like this:

project={
         prop,
         prop,
         prop, 
         qp:{
             prop,
             prop,
             prop, 
             questions:[
                        question:{
                                  prop,
                                  prop,
                                  prop, 
                                  answers:[
                                           answerModels<--!this i want to find and edit!-->
                                          ]
                                 }
                        ]
            }

}

2 Answers 2

1

You should consider FindOneAndUpdate function of Mongoose.

This will allow you to find your document, edit it and save it back in your MongoDB.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I tried that but I didn't get it to work, you see my object is kinda complex project={prop,prop,prop, qp:{prop,prop,prop, questions:[question:{prop,prop,prop, answers:[answerModels<--!this i want to find and edit!-->]}]}}
0

I solved it like this:

projectModel.findById({_id: req.body.projectId},function (err, doc)
  {
    if(err)
    {
      console.log(err)
      return;
    }
    for (i in doc.qp.questions) {
      if(doc.qp.questions[i]._id == req.body.questionId)
      {
        for(y in doc.qp.questions[i].answers)
        {
          if(doc.qp.questions[i].answers[y]._id == req.body.answerId)
          {
            var test = doc.qp.questions[i].answers[y].value
            console.log(test);
            var query = "qp.questions"+i+"answers."+y+".value";

            doc.update({_id: req.body.questionId}, { '$set': {query : req.body.answerValue} });
            console.log(doc.qp.questions[i].answers[y].value);
            doc.save().then(() => res.send({questionId: req.body.questionId,answerId: req.body.answerId,answerValue: req.body.answerValue}))
          }
        }
      }
    }
  })
  .catch(error => console.log(error))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.