Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

293
Vistas
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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

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}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda