skip to Main Content

I am using mongoose to store user data, and one of the attributes is items: [] in my additems.js:

const User = require('../models/User');
var array = user.items
        array.indexOfObject = function (property, value) {
            for (let i = 0, len = this.length; i < len; i++) {
              if (this[i][property] === value) return i;
            }
            return -1;
          }
        let indexofarray = `items.${array.indexOfObject("item",`${item.name}`)}.quantity`
        User.findOneAndUpdate({username:"username"},
            {
               $set:{
                indexofarray: array.item.quantity++
               }
            }).then(err => {
                console.log(err)
            })

i want to increase the quantity of the given item in the array which is straight forward. But i dont know where the item is going to be in the array so I have to get it using a function. But i cant throw that in there because it doesn’t take variable’s or item.${array.indexOfObject("item",${item.name})}.quantity. Is there a way to do this? Or a different way to achieve this result?

any help towards the right direction helps!

2

Answers


  1. Chosen as BEST ANSWER

    I found an answer online that works! simply, all you have to do is add brackets [] and then but a variable inside or in quotes like I did.

    $set: {
          [`item.${item}.quantity`]: quantity++
        }
    

  2. So, you want to update item.quantity for a give item.name, where item is an array.

    You can use $[]. No need to find the index first.

    User.findOneAndUpdate(
    {username: "username"},
    {
        $inc:{"item.$[elem].quantity": 1}
    },
    {arrayFilters: [{"elem.name": "value"}]}
    )
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search