Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda