2

I was trying to do an update operation. Now I'm getting an immutable error I knew the cause it was updating the key. I wonder because I'm not passing the _id from the API still I can see the _id if I console. I want to remove the _id from my object in order to fix this error. Code below

 router.put('/:id', (req, res) => {
    //var findid= req.params.id;
    if (!ObjectId.isValid(req.params.id))
        return res.status(400).send(`No record with given id : ${req.params.id}`);

        var alum = new Alumni({
            fname: req.body.fname,
            lname: req.body.lname,
            contact: req.body.contact,
            gender: req.body.gender,
            dob: req.body.dob,
            message: req.body.message,
            city: req.body.city,
            pincode: req.body.pincode,
            state: req.body.state,
            district: req.body.district,
            password: req.body.password,
            email: req.body.email

    
        });
        //delete alum['_id'];
    Alumni.findByIdAndUpdate(req.params.id, { $set: alum }, { new: true }, (err, doc) => {
        if (!err) { res.send(doc); }
        else { 
            console.log(alum);
            console.log('Error in Alumni Update :' + JSON.stringify(err, undefined, 2)); }
    });
});

How can I resolve this error?

1 Answers1

0

Whenever JSON object is assigned using mongoose model like new Alumni(), by default it assigns _id field which is immutable so you don't need to use model with update object. Simply assign it as given below

var alum = {
    fname: req.body.fname,
    lname: req.body.lname,
    contact: req.body.contact,
    gender: req.body.gender,
    dob: req.body.dob,
    message: req.body.message,
    city: req.body.city,
    pincode: req.body.pincode,
    state: req.body.state,
    district: req.body.district,
    password: req.body.password,
    email: req.body.email
};