Home > Back-end >  How to increment a value which is in an object which is in an array which is in another object
How to increment a value which is in an object which is in an array which is in another object

Time:01-09

So I'm trying to code a bot in discord.js where you basically have items in an inventory and when I use an item, its durability goes down. I am using MongoDB Atlas to store all the data. The structure of the inventory is:

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

So I just wanted to find a way to basically just decrement the durability in the item without updating any other item in the inventory array but I wasn't able to get a way to do it.

CodePudding user response:

You can use arrayFilters to update only the value you want.

Also you can use $inc to increment the value (in this case increment by -1, i.e, decrement)

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

Example here

CodePudding user response:

I think it worked but a new error popped up saying: MongooseError: Callback must be a function, got [object Object]. I checked this error in Google and people were saying that this was due to a syntax error according to this => MongooseError: Callback must be a function, got [object Object]. My code was like this:

const updatedUserData = await profileSchema.findOneAndUpdate({
    userId: interaction.user.id
}, {
    "$inc": {
        "inventory.$[element].number": 1
    }

}, {
    "arrayFilters": [
        {
            "element.id": "stone"
        }
    ]
}, {
    upsert: true
})

But when I moved the arrayFilters into the $inc object like this:

const updatedUserData = await profileSchema.findOneAndUpdate({
   userId: interaction.user.id
}, {
   "$inc": {
       "inventory.$[element].number": 1
    },
    "arrayFilters": [
       {
           "element.id": "stone"
       }
   ]
}, {
    upsert: true
})

a new error came saying MongoServerError: No array filter found for identifier 'element' in path 'inventory.$[element].number'

  •  Tags:  
  • Related