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

145
Views
Update mongo collection with values from a javascript map

I have a collection that looks like this

[
   {
      "project":"example1",
      "stores":[
         {
            "id":"10"
            "name":"aa",
            "members":2
         }
      ]
   },
   {
      "project":"example2",
      "stores":[
         {
            "id":"14"
            "name":"bb",
            "members":13
         },
         {
            "id":"15"
            "name":"cc",
            "members":9
         }
      ]
   }
]

I would like to update the field members of the stores array taking getting the new values from a Map like for example this one

0:{"10" => 201}
1:{"15" => 179}

The expected result is:

[
       {
          "_id":"61",
          "stores":[
             {
                "id":"10"
                "name":"aa",
                "members":201
             }
          ]
       },
       {
          "_id":"62",
          "stores":[
             {
                "id":"14"
                "name":"bb",
                "members":13
             },
             {
                "id":"15"
                "name":"cc",
                "members":179
             }
          ]
       }
    ]

What are the options to achieve this using javascript/typescript?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use update() function of Mongoes model to update your expected document. Try following one:

const keyValArray= [{"10": 201},{"15":"179"}];
db.collectionName.update({_id: givenId},
       { $push: { "stores": {$each: keyValArray} }},
       function(err, result) {
          if(err) {
             // return  error
          }
          //return success
       }
});
about 4 years ago · Juan Pablo Isaza Report

0

In the end, I resolved by updating the original database entity object with the values in the map, then I have generated a bulk query.

for (let p of projects) {
    for(let s of p.stores) { 
        if(storeUserCount.has(s.id)){
            s.members = storeUserCount.get(s.id);
        }
    };
    bulkQueryList.push({ 
        updateOne: {
            "filter": { "_id": p._id },
            "update": { "$set": {"stores": p.stores} }
        }});
};

await myMongooseProjectEntity.bulkWrite(bulkQueryList);
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!