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

232
Vistas
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 Respuestas
Responde la pregunta

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