【问题标题】:Save document after subdocument been updated mongoose, mongodb子文档更新后保存文档猫鼬,mongodb
【发布时间】:2018-07-12 19:20:56
【问题描述】:

我想更新子文档的值,然后保存主文档。因此,对子文档的更改将保存到数据库中。 这是我的代码ATM, 我找到了正确的子文档,这不是我猜的问题。但它不会保存更改。

 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))

我的对象有点复杂,它必须是......它看起来像这样:

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

}

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    你应该考虑猫鼬的FindOneAndUpdate功能。

    这将允许您找到您的文档,对其进行编辑并将其保存回您的 MongoDB。

    【讨论】:

    • 是的,我试过了,但我没有让它工作,你看我的对象有点复杂 project={prop,prop,prop, qp:{prop,prop,prop, questions:[问题:{prop,prop,prop,答案:[answerModels]}]}}
    【解决方案2】:

    我是这样解决的:

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 2017-10-05
      • 2020-02-26
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多