Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error while updating a document in MongoDB

I am having an admin portal in which I am handling all the collections that exist in my Mongo database. Now, I am building the update operations. I want to find a user that exist with his username and update the document with the changes that the admin performed.

For that reason, in my controller I have an endpoint which do the following:

exports.updateUser = async(req, res) => {
  try{
    var user = new User({
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      username:req.body.username,
      password: req.body.password,
      email: req.body.email
    });
    const static_username = req.body.static_username;

    await User.findOneAndUpdate({static_username} , user, { useFindAndModify: false})
    .then(data => {
        if(!data){
          res.status(404).send({ message : `Cannot Update user with ${id}. Maybe user not found!`})
        }else{
          res.redirect('/admin');
        }
    })
    .catch(err =>{
        res.status(500).send({ message : "Error Update user information"})
    })
  } catch {
    console.log(err);
  }
}

It takes the changes that the admin has made from the body and it puts them into user object. I also set to the variable static_username the username before update in order to find the user I to make the update.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am getting a response that exist inside the catch of the query:

{ message : "Error Update user information"}

Error:

MongoServerError: Plan executor error during findAndModify :: caused by :: Performing an update on the path '_id' would modify the immutable field '_id'

Any thoughts why found user doesn’t get updated?

>Solution :

You are sending a User object which has an _id field by default. So, unknowingly you are trying to modify the _id field and setting it to zero. To solve this, you can simply send a normal object.

var user = {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      username:req.body.username,
      password: req.body.password,
      email: req.body.email
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading