我想更新子文档的值,然后保存主文档。因此,对子文档的更改将保存到数据库中。 这是我的代码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!-->
]
}
]
}
}
答案 0 :(得分:1)
您应该考虑使用猫鼬的FindOneAndUpdate功能。
这将使您可以找到文档,对其进行编辑并将其保存回MongoDB中。
答案 1 :(得分:0)
我这样解决了:
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))