Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!