Noob Master
Noob Master

Reputation: 111

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

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);

                
        }

    })

    })

Upvotes: 0

Views: 2981

Answers (3)

Dario Palminio
Dario Palminio

Reputation: 89

The idea is to never pass in the values ​​to update the '_id', instead you can extract the id from the entity and send the other values. For example:

const unmarshalled = Employee.unmarshal(); 
const {_id, ...values} = unmarshalled;
const doc: Document = await model.findByIdAndUpdate(_id, values, { useFindAndModify: false }).exec();

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31193

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) => {

Upvotes: 2

NeNaD
NeNaD

Reputation: 20354

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." })
    }
  })
})

Upvotes: 0

Related Questions