I am working on a NodeJS project. I am using express and mongoose. I am trying to update a document in MongoDB but updates are not showing up. Also, there is no error as the page is getting redirected as per res.redirect(‘/content/contnet-view/’+id)
router.post('/posthere', function(req, res){
const { id, Status, ModuleIndex, ItemIndex } = req.body;
Content.findOne({_id: id}, function(err, foundContent){
if(err){
console.log(err);
res.status(500).send();
}else{
if(!foundEnroll){
res.status(404).send();
}else{
if(id){
foundContent.ContentData.ContentM[ModuleIndex].ContentI[ItemIndex].Status = Status;
}
foundContent.save(function(err, updateContent){
if(err){
console.log(err);
res.status(500).send();
}else{
res.redirect('/content/contnet-view/'+id)
}
})}}
})})
Any idea what I am doing wrong here?
2
Answers
It was an issue with misconfigured Schema. matching it with the Document format fixed it.
Using findByIdAndUpdate is better approach but in this case, mongoose save function returns a promise object.
If
save()
succeeds, the promise resolves to the document that was savedYou need to use thenable chain approach to handle async function instead of callback