Search code examples
node.jsmongodbmongoosefindby

findByIdAndUpdate Don't Work Mongoose MongoDB


enter image description here

I try to update the data in MongoDB Compass via Nodejs in the picture by using findByIdAndpUpdate.

Below is the code that I wanna to update name, price, description with the same _id:

router.post('/update',(req,res)=>{
    //new data from edit form
    const update_id = req.body.update_id
    let doc = {
        name: req.body.name,
        price: req.body.price,
        description: req.body.description
    }
    console.log("New data from form :", doc)
    console.log("ID :", update_id)
    Product.findByIdAndUpdate(update_id,doc,{useFindAndModify:false})
    res.redirect('/manage')
})

enter image description here

This is what happened when I run the code in VSCode. Nothing seem to happens in MongoDB compass.

Everything still the same even I sent the update data in my new form to MongoDB compass see in picture.


Solution

  • The mongoose findByIdAndUpdate() method is an asynchronous task. This means it returns a Promise that you need to either chain a then() block to and wait for the task to complete or adopt the async/await pattern.

    A simple fix to get your code working would be to use the latter like so:

    router.post('/update', async (req,res)=>{ //< Mark callback function as async
       try{
          //new data from edit form
          const update_id = req.body.update_id
          let doc = {
            name: req.body.name,
            price: req.body.price,
            description: req.body.description
          }
          console.log("New data from form :", doc)
          console.log("ID :", update_id)
          const updatedDoc = await Product.findByIdAndUpdate(update_id, doc, {new:true}); //< Use of await and assign return value to variable 
          res.redirect('/manage')
       }catch(err){
          console.log(err);
          //Handle error
       }
    });
    

    You will notice I have included the option {new:true} in the findByIdAndUpdate. This tells mongoose to return the updated document i.e it has the changes applied. I have not included the {useFindAndModify:false} as this option is only required if using with older versions of mongoose such as V5.x. See here further details. If you are using an old version of mongoose I would encourage you to please update to V7.x but if your organisation can't then you can of course add the option back in.