Can you provide guidance on how to increase the value within a nested object located inside an array within another object?

In my attempt to create a bot in discord.js, I am facing a challenge where I need to implement an inventory system with items that have durability. The data is stored in MongoDB Atlas and the structure of the inventory is as follows:

user: {
  id: 'user-id',
  name: 'user-name',
  inventory: [
    {
      name: 'item',
      durability: 5
    ,
    {
      name: 'another-item',
      durability: 20
    }
  ]
}

I am looking for a way to decrement the durability of an item in the inventory without affecting any other items in the array, but I haven't been able to find a solution so far.

Answer №1

If you want to update only specific values, you can utilize arrayFilters.

Another option is to use $inc to increment the value (in this case, decrement by 1).

db.collection.update({
  "id": "user-id"
},
{
  "$inc": {
    "inventory.$[element].durability": -1
  }
},
{
  "arrayFilters": [
    {
      "element.name": "item" //Replace with the object name you want to update
    }
  ]
})

For an example, check this link.

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

What is the best way to transfer data in a JavaScript onclick event and then retrieve it in the click handler function?

I've been struggling with this issue for some time now. When researching the onclick JavaScript call, I noticed that sometimes it is written as onClick with a capital C, while other times it's simply onclick. The code I'm working on is part ...

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

What seems to be causing the malfunction in this ranking function?

I created a custom function to retrieve the top five users from a JSON database. Below is the code snippet: var users = []; Object.keys(database).forEach(user => { if (!users[0]) { users[0] = user } else { var checked = false; for (let ...

Is there a way to dynamically update the target of a form using JavaScript?

My goal is to change the target of a form in order to open a new window. However, all redirections of this form use the same window except for one specific button. This button calls a custom JavaScript function that needs to change the default "_self" targ ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...

The Mongoose Populate method for fetching users is throwing a 404 error (access denied)

I am facing an issue while trying to populate the users array within a project. I am encountering the error GET http://localhost:9000/api/users 403 (Forbidden) when logged in, and GET http://localhost:9000/api/users 403 (Unauthorised) when not logged in. T ...

Technique for updating URL when submitting a form on a webpage

I'm a newcomer to the world of coding and I have a simple issue that needs fixing. I want to create a form field where users can input the last segment of a URL provided to them. After entering this segment, I want the page to refresh automatically a ...

Transferring multiple data between PHP and JavaScript

Here is the code I am using for the on change event: <script> $('.BIR').change(function() { var id = $(this).val(); //get the current value's option $.ajax({ type:'POST', dataType: "json", ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

What is the best way to extract JSON data from a remote URL?

Having recently started with JavaScript, I am looking to parse JSON from an external URL using pure JavaScript. Currently, I have the following code: var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, tr ...

Challenges with JavaScript fetching JSON information

Resolved: To enable AJAX functionality, I needed to upload the files to my server. Currently, I am attempting to retrieve stock information from a JSON file, but no data is being displayed. Upon alerting ajax.status, it returned 0 as the result, indicatin ...

Build a Search Suggestions feature with Node Package Manager (NPM) and Model-View-Controller (M

Stepping into the exciting world of MVC core and harnessing NPM for JavaScript packages has been a learning curve. However, I've encountered an issue that requires some deliberation on the best course of action for resolution. To provide context, I ha ...

Guide to converting raw Mysql fields into objects using Node.js

I have written a code to retrieve all the rows from the article table in MySQL, but I would like to represent this data in object and array format so that I can send it to endpoints. app.get('/article' , function(req , res){ var connec ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Tabindex issue arises due to a conflict between Alertify and Bootstrap 4 modal

When trying to call an Alertify Confirmation dialog within a running Bootstrap 4 Modal, I encountered an issue with the tab focus. It seems to be stuck in the last element and not working as expected. I suspect that this might have something to do with th ...

Retrieving a Collection of Items Generated in the Past Day from a Specific Dataset Using JavaScript

I have been tasked with extracting a specific set of arrays from given data based on a 24-hour time frame using the timestamps provided. I initially attempted the code below, but unfortunately, it kept returning the same data to me. I suspect there may be ...

Access your login page with a nodejs mongoDB connection

After successfully sending username, password, and email through postman, the information gets added to the MongoDB schema. However, on the login page in React, it doesn't seem to work correctly. Any assistance would be greatly appreciated. Thank you. ...

List of items displayed in alphabetical order using the ng-repeat directive:-

I'm working with an ng-repeat block in the code snippet below. My goal is to have the placeholder [[THE ALPHABET]] render as a, b, c, d representing bullets for the list in their respective order. There will always be 4 values present. What would be t ...

Prevent the date each month in asp.net

Is there a way to block Sundays for all months and years in a text box with the Text mode set to Date? <asp:TextBox ID="txtfromdate" runat="server" Enabled="True" OnTextChanged="From_TextChanged" TextMode="Date" ></asp:TextBox> ...