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

231
Visualizações
React: How to Add and update Elements into an Array in MongoDB

I am sending a new item to the database and inside that data there is an array with some id. I'm using node and expressJs. So, the idea is If there is an object exists, I want to update the array inside the object. Or the object will be created in mongodb.

The Issue is: On first submit it adds to the database with an array. But on other clicks the array just got replaced with new Id.

 app.put("/destination", async (req, res) => {
      const email = req.query.email;
      const query = { email: email };
      let result;
      if (query) {
        const cursor = userCarCollection.find(query);
        const userNewIds = req.body;
        result = await collection.updateOne(
          query,
           { $set: userNewIds },
          { upsert: true }
        );
      } else {
        result = await carCollection.insertOne(userNewCar);
      }
      res.send(result);
    });

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I found the solution guys. Sorry for any inconvenience. I had to use $push method not $set method. As, I am a beginner I couldn't think that way. My solution is as follows and it's working perfectly:

if (query) {
        const cursor = userCarCollection.find(query);
        const userNewIds = req.body.productId.toString();
        result = await userCarCollection.updateOne(
          query,
          {
            $push: {
              productId: userNewIds,
            },
          },
          { upsert: true }
        );
      }

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