How can I add new objects to an array in MongoDB?

Currently, I am facing a challenge in my project which involves utilizing MongoDB as the database. Specifically, I am struggling with updating an array of objects within the schema outlined below:

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

My goal is to have a single array containing objects, and each of these objects should consist of two nested objects.

In essence, I am looking to have Plays Array [ object1, object2] where object 1 would be {player 1 : {card1 : 0, card2 : 0}}, {player 2 : {card1 : 0, card2 : 0}}.

Despite my attempts to write an updateOne function, I am encountering issues where it only updates player 1 or splits player 1 and player 2 as separate items in the array. Can you provide any insights into what might be causing this formatting error?

For reference, here is the code snippet I am currently using:

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

While the code executes successfully, the issue lies in how it pushes player 1 and player 2 separately into the array, resulting in a structure like [ player 1/2 objects, player 1 objects, player 2 objects ].

Answer №1

Oops! I forgot to include [ ] around the object in a previous version that didn't use $each. Keeping this here in case it helps someone else.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display and conceal element selections within my specific situation

Struggling with hiding elements on a page? I've been utilizing a script to create a multiselect dropdown element that serves as the main controller for elements on the page (). The script returns an array of selected elements while my elements have ...

Exploring 2D Array Zones Using Python

Imagine having the following 2d array: [ [1,1,1,2,2], [1,1,2,3,2], [2,2,2,3,1], [2,1,0,3,2], [2,0,3,3,0]] In this array, there are zones with the same values. If a zone has 5 or more cells, those values turn into zeros, resulting in this new array: [ [0 ...

Web audio: setTimeout slows down when mobile screen is turned off

In response to Yogi's feedback (refer to the discussion on "setTimeout" and "throttling" in https://developer.mozilla.org/en-US/docs/Web/API/setTimeout ), I attempted to enhance performance by integrating an AudioContext. document.addEventListener(&ap ...

Instructions for sketching a square at predetermined coordinates

Looking for a simple function to draw a box at specific coordinates x and y. I've searched for guides, but they all seem to provide excessive or insufficient information. Thanks in advance! ...

What is the method for displaying HTML newlines in PHP?

Within a <textarea>, I input multiple numbers on separate lines by pressing enter. When I submit the form, these numbers are received on the server side as 'X'. However, when I echo 'X' to the browser, the numbers are separated by ...

Retrieve all Mongodb documents through aggregation where the foreign document from $lookup does not exist

Currently, I am dealing with a CMS system that does not delete associated content when pages are removed. This has become problematic for one of my clients as we now have millions of accumulated content documents, making daily tasks like restoring and back ...

Emphasize the letter by pressing the shift key along with either the left arrow

When the right and left arrow keys are pressed, my HTML element currently only highlights the next letter when the shift key is also pressed. How can I modify it to highlight all the letters in the word when the shift key and the right or left arrow keys a ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

What is the command to manually reboot MongoDB in the terminal?

I recently set up mongodb in VS code using the command npm install mongodb. However, I also downloaded mongodb from the official website and installed it as a Windows service because I was unsure if the installation in vscode with npm was sufficient. Every ...

AngularJS advanced array filtering techniques

Seeking to enhance my search capabilities using an Angular filter. This particular filter is designed to take in two values (maximum and minimum) within an array, and then extract all intervals that fall between the maximum and minimum of another array. F ...

Navigating Angular on Internet ExplorerUnderstanding Angular's Compatibility

Having some trouble with an Angular app I'm developing. It displays perfectly on Chrome, but not at all on IE. Any tips on how to configure IE to show it correctly, or should I make changes to the app to ensure compatibility with IE? You can see how i ...

A comprehensive guide on how to find keywords within an array and then proceed to make all text within the parent div tag stand

I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script ...

Creating a curved surface in Three.js: A simple guide

Currently, I am working on a project where I am projecting a video into 3D geometry using the Three.js library. The source footage is from a GoPro camera with a field of view around 120 degrees. My goal is to create a visual effect where the video appears ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

Struggling to utilize the filter technique in JavaScript?

Hey there, I'm facing a challenge in my JavaScript course. The exercise requires the creation of a function that filters an array to only keep strings with less than 10 characters. I've made several attempts at solving this problem, but haven&ap ...

Where to Locate a String Excluding <a> Tags?

I'm in the process of writing a JavaScript code that will scan an HTML document and identify all occurrences of a specific keyword that are NOT contained within a link, meaning not under an <a> tag. To illustrate this, let's examine the fol ...

HTML Canvas Width Specification

Struggling with it is the initial width of my canvas. My setup consists of a canvas element with an image background set to cover. Using jQuery, the canvas width is set to window.innerWidth while the height is calculated as one-third of the width (to main ...

Record the end time of a JavaScript stopwatch and save it into a PHP variable

I have implemented a stopwatch feature using the following JavaScript code: <script language="JavaScript" type="text/javascript"> window.onload = function() { stopwatch('Start'); } <!-- var sec = 0; var min = 0; var hour = 0; functio ...

What is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...

Bat scripts using loops and arrays to iterate through variables i and j are displaying a blank command window instead of running the intended programs. I am intent on preserving the functionality of the i and j loops while troubleshooting this

Running cmd commands opens empty command prompt windows `@echo off REM The echo off and other things don't work with power shell, only with cmd, another reason why wasn't working setlocal enabledelayedexpansion set FileTasks[0]=1 - Open task man ...