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

105
Vistas
updateOne does not update multiple fields and does not create new fields in a record

I am using NodeJs and MongoDB atlas for saving/updating user profiles. However, the updateOne method does not update multiple fields and I do not know why! It only works for one variable and not for the whole record! Here is my code:

app.post("/edit-profile", async (req, res) => {
  if(req.body.password || req.body.phoneNumber){
    res.status(401);
    res.send({"error": "this api is not for changing password or phoneNumber"})
  } else {
    console.log("let's update this user: id="+req.body.id)
    console.log(req.body)
    result = User.updateOne(
      { _id: ObjectId(req.body.id)},
      req.body,
      (error, result) => {
        if (error) {
          console.log(error);
          res.status(400);
          res.send();
        } else {
          if (result.n > 0) {
            console.log("result")
            console.log(result)
            res.header({ sessionToken: "testToken" });
            res.send(req.body);
          } else {
            console.log("there is no user with this id")
            res.status(404);
            res.send({"message":"There is no user with this id!"});
          }
        }
      }
    );
  }
});

for example whenever, when I have it works for

{
    "id":"6253024ca9a2fb3a9a8d3675",
    "weight":888
}

but does not work for

{
    "id":"6253024ca9a2fb3a9a8d3675",
    "height":999
}

only works for weight parameter and does not create a new field (height). Even I used multiple fields at the same time and got the same results. Also, I have another API for updating the meals item and it has a similar structure and it works. Here is my code for this API:

app.post("/edit-meals", async (req, res) => {
  const { error } = mealSchema.validate(req.body);
  if (error) {
    res.status(400); // 400 bad request
    res.send(error.details[0].message);
  } else {
    const meal = await Meal.findOne({ title: req.body.title });
    if (meal) {
      Meal.updateOne({ title: req.body.title }, req.body, (err, result) => {
        if (err) {
          res.status(403);
          res.send;
        } else {
          res.send(req.body);
        }
      });
    } else {
      res.status(404);
      res.send();
    }
  }
});

Although the updateOne works in the edit meals but it does not work in edit user. I would be grateful if anybody could help me through this.

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

0

Check if your User model has all of the fields defined. Mongoose will ignore all the properties that are not present inside the model.

So, check the User schema and see if there is height field defined.

about 4 years ago · Juan Pablo Isaza Denunciar

0

    app.post("/edit-meals", async (req, res) => {
  const { error } = mealSchema.validate(req.body);
  if (error) {
    res.status(400); // 400 bad request
    res.send(error.details[0].message);
  } else {
    const meal = await Meal.findOne({ title: req.body.title });
    if (meal) {
      Meal.updateOne({ title: req.body.title }, {{$set:{field: value}}}, (err, result) => {
        if (err) {
          res.status(403);
          res.send;
        } else {
          res.send(req.body);
        }
      });
    } else {
      res.status(404);
      res.send();
    }
  }
});

try this {field: value}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use updateMany to update multiple documents in mongoDb.

updateMany({data})

To add a new field in mongodb document use

updateMany({_id: ObjectId(req.body.id)},{$set:{key:value}})
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