简体   繁体   中英

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.

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?

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

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM