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')
})
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.
2
Answers
I've tried this code,
It seems fine in VSCode. (new data has been updated to previous ID).enter image description here
However in MongoDB Compass it didn't update to new data to the ID. enter image description here
How can I configure MongoDB Compass to automatically update new data for this function?
For your reference, I use Mongoose 7.6.3 and MongoDB Compass 7.0.2 enter image description here enter image description here
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:
You will notice I have included the option
{new:true}
in thefindByIdAndUpdate
. 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.