skip to Main Content

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


  1. Chosen as BEST ANSWER

    It was an issue with misconfigured Schema. matching it with the Document format fixed it.


  2. 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 saved

    doc.save().then(savedDoc => {
           savedDoc === doc; // true
           });
    

    You need to use thenable chain approach to handle async function instead of callback

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search