我想更新子文档的值,然后保存主文档。所以对子文档的更改被保存到数据库中。 这是我的代码 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!-->
]
}
]
}
最佳答案
你应该考虑FindOneAndUpdate Mongoose 的功能。
这将允许您找到您的文档,对其进行编辑并将其保存回您的 MongoDB 中。
关于javascript - 更新子文档后保存文档mongoose,mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287202/