Updating a specific field within an array in a Meteor object using MongoDB

I have a document with game details and participants. Here is an example of the structure:

{
   "gameName":"Shooter",
   "details":[
      {
         "submitted":1415215991387,
         "author":"XYZ",
         "subPlayer":{
            "members":{
               "squad1":[
                  {
                     "username":"John",
                     "deaths":0
                  }
               ]
            },
            "gameSlug":"0-shooter"
         }
      }
   ],
   "userId":"foL9NpoZFq9AYmXyj",
   "author":"Peter",
   "submitted":1415215991608,
   "lastModified":1415215991608,
   "participants":[
      "CXRR4sGf5AdvSjdgc",
      "foL9NpoZFq9AYmXyj"
   ],
   "slug":"1-shooterConv",
   "_id":"p2QQ4TBwidjeZX6YS"
}

... along with a Meteor method that needs to update the deaths field in the document:

Meteor.methods({
    updateDeaths: function(gameSlug, user, squad) {
            Stats.update({details.subPlayer.gameSlug: gameSlug}, ...}); // ???
    }
});

The goal is to update the deaths field using the user object (with username = user.username) and the squad name as string (squad1). Any suggestions on how to achieve this would be appreciated.

Your guidance is greatly valued.

Answer №1

Here is an example of how you can achieve this:

db.collection.update(
  {'userId':'foL9NpoZFq9AYmXyj', 'details.subPlayer.gameSlug':'0-shooter'}, 
  {'$set': 
     {'details': [{
          'subPlayer': {
               'members': {
                  'squad1':[{'username':'John','death':1}]
               }
          }
       }]
     }
  }
)

UPDATE:

You could also consider using find().snapshot().forEach() which might be a more efficient way, depending on how Meteor handles it. Here is an example:

Stats.find({'userId':'foL9NpoZFq9AYmXyj', 'details.subPlayer.gameSlug':'0-shooter' }).map(function (e) {
    e.details.forEach(function (d) {
        var squad = 'squad1';
        d.subPlayer.members[squad].forEach(function (s) {
            s.deaths = 10000;
        });
    });
    Stats.update({'_id': e._id}, e);
});

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

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

Issue with Electron and Node.js: Application fails to launch due to inability to locate the app within the modules

I am currently testing out an electron application that is supposed to link to our website. I decided to follow one of the tutorials available. Unfortunately, upon launching the app, I encountered the following error: Error log : akshay@akshay-mint-deskt ...

Customize Your Greasemonkey Script Timeout

At our organization, we utilize the Firefox Greasemonkey addon to automatically enter login credentials on a specific webpage upon opening it. Here is an example of what the script consists of: // ==UserScript== // @name logon // @namespace http ...

Tips for maintaining the full width/height ratio of a child image when covering a fixed size container

I have a square container with dimensions of 300x300 and an <img src="" /> image inside. My goal is for the image to cover the entire container while maintaining its width/height ratio. If the image's width is smaller than its height ...

Spin a three-dimensional cube on a platform using three.js with a unique functionality

I am attempting to create an animation featuring a cube on a flat surface. The cube can be rotated along the x/y axis only, with no need to show its underside. I want to be able to tip the cube over any edge - when a side of the cube touches the surface, i ...

What is the interaction between Vue's v-model and the update:modelValue directive, and how can we customize the default behavior to prevent it from

Could someone provide an explanation of the usage of v-model with :modelValue and update:modelValue? What happens when both are used together? In the code snippet below, a component is shown: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3. ...

Alert: It is invalid for an <a> element to be nested inside another <a> element according to validateDOMNesting

I've been experimenting with using react-router in conjunction with reactstrap and create-react-app. While setting up the routing within my application, I encountered a need to utilize state for the reactstrap components. To achieve this, I converted ...

Can you explain the process of utilizing WebdriverIO (wdio) to determine the frequency of an element's occurrence?

Currently, I am working on creating an interaction test to validate my javascript code using WebdriverIO (wdio). The specific functionality I am looking to test involves deleting a node and verifying that the number of times a selector appears has decreas ...

Error: Unable to locate the tslint command

After attempting to utilize tslint --fix, I encountered the error message bash: tslint: command not found.... To install tslint, I ran the following command: yarn global add tslint typescript. The operating system on my machine is Centos 7. ...

Injecting dynamic data into a function parameter with Angular 1 Interpolation

In my code, I have a feature that alters the text displayed on a button depending on certain conditions. $scope.text = 'Wait'; if(Number($scope.x) == Number($scope.y)) $scope.text = 'Go' else if(Number($scope.x) < Number($scope ...

Implement a hover effect on a specific class targeting a nested element using JavaScript

Is there a method to apply a class that modifies rules for a child element using Javascript? I have successfully added it with CSS but am struggling to do the same with Javascript. Removing the class in JS is easy by referencing the classname before the ho ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

Retrieving data from AJAX requests

I have an AJAX code that sends data to the server and returns results including id, name, and quantity. How can I extract and print only the quantity, id, or name? Thank you for your help! <script type="text/javascript"> $("#bto_update_quan ...

Using a combination of radio buttons and JavaScript to adjust the color of a div element

Currently, I am experimenting with radio buttons to modify the background color of my div tag. My goal is to incorporate more than one condition. For example, if button A and button B are both clicked, then change the color to green. This is what I have im ...

Node.js: Verifying the user's previous login status using Passport

My current express router for users handles user logins using a token system: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var Veri ...

Several JavaScript functions require a confirmation dialog to be displayed before they can be executed

There are three separate javascript/jquery functions in my code, all triggered by a button click. One function posts to a form handler, another creates a new tab, and the third one sends new data into the tab through an ajax call. These functions are inter ...

Issue with the System.Web.HttpRequestValidationException

I've been grappling with an issue related to a week-long problem that involves the error message System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client. This issue arises specifically when de ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

Which one should I use: ng-repeat or ng-options?

I am looking to display JSON data in a dropdown list, and I have two options to choose from. The first option is using ng-repeat, while the other option is ng-options. Using ng-repeat: In the HTML file: <select> <option ng-repeat="prod in testA ...