Home > database >  Error while updating a document in MongoDB
Error while updating a document in MongoDB

Time:07-03

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.

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?

CodePudding user response:

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

CodePudding user response:

I think that the update input should contain only the fields you want to update. if username is the unique id in you User model, you would need to delete it from the user object - delete user.username - before passing it to findOneAndUpdate because an id cannot be updated. Also, as mentioned in the comments, try replacing the filter with { username: static_username}

  • Related