Home > Net >  MongoServerError: Performing an update on the path '_id' would modify the immutable field
MongoServerError: Performing an update on the path '_id' would modify the immutable field

Time:09-17

I was trying to make a CRUD app in Nodejs using MongoDB but when I wrote the update part and send the send using postman it's showing the error in the terminal that

**MongoServerError: Performing an update on the path '_id' would modify the immutable field '_id'**

Here's my code to update an entry bu _id in mongo db

    router.put('/api/employee/edit/:id' ,(req,res) =>{

    const emp = new Employee({
        
        
        name:req.body.name,
        email:req.body.email,
        salary:req.body.salary
    });
    Employee.findByIdAndUpdate(req.params.id, {$set: emp},(err,data) => {

        if(!err){
                res.status(200).json({code:200,message:"Employee updated successfully",
            updateEmployee:data
            
            })
           

        }
        else{
            console.log(err);

                
        }

    })

    })

CodePudding user response:

I’m assuming giving the whole object as an argument to $set means it will try to modify all properties of it, including _id which shouldn’t be modified and you haven’t set on the object. Try to specify the properties to modify separately:

Employee.findByIdAndUpdate(req.params.id, {$set: {
    name:req.body.name,
    email:req.body.email,
    salary:req.body.salary
}},(err,data) => {

CodePudding user response:

You are creating a new Employee document and wants update the current one with that new one. You can not do that since that will also try to override _id of the document. Instead of creating a new Employee document, you should just update existing one with new data:

router.put('/api/employee/edit/:id', (req, res) => {

  Employee.findByIdAndUpdate(req.params.id, {
    name: req.body.name,
    email: req.body.email,
    salary: req.body.salary
  }, { new: true }, (err, data) => {
    
    if (!err) {
      res.status(200).json({ code: 200, message: "Employee updated successfully", updateEmployee: data })
    } else {
      res.status(400).json({ code: 400, message: "Employee updated failed." })
    }
  })
})
  • Related