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

109
Views
Mongo DB Push to Array of Objects?

Working on a project that uses MongoDB as a database. I'm stuck on trying to get an array of objects I have to update. Here is the schema:

roundData : {
                playsArray : [ 
                    {
                        player1 : {
                            card1 : 1,
                            card2 : 2
                        },
                        player2 : {
                            card1 : 0,
                            card2 : 0
                        }
                    },
                ],

So basically I want a single array that holds an object within that object are two objects.

Plays Array [ object1, object2] where object 1 would be {player 1 : {card1 : 0, card2 : 0}}, {player 2 : {card1 : 0, card2 : 0}}.

Every time I try to write an updateOne function, it at best only updates player 1 or it seperates player 1 and player 2 as two items in the array. Any suggestions what I'm doing wrong on the formating?

Here's my current code:

const gameData = await GameData.updateOne({ gameId: gameIdInput }, { $push: { "matchData.roundData.playsArray": { $each : [ {"player1" : {"card1" : 0, "card2" :0} }, {"player2" : {"card1" : 0, "card2" :0} } ] } } } );

This works, but it pushes player 1 and player 2 into the array separately so that the array becomes [ player 1/2 objects, player 1 objects, player 2 objects ].

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Nevermind! I was missing [ ] around the object in a previous version without $each. Leaving here for solution if anyone finds it helpful.

const gameData = await GameData.updateOne({ gameId: gameIdInput }, { $push: { "matchData.roundData.playsArray": [ {"player1" : {"card1" : 0, "card2" :0} }, {"player2" : {"card1" : 0, "card2" :0} } ]  } } );

about 4 years ago · Santiago Gelvez 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!