Home > Enterprise >  $set { "array.index.value" :"newvalue"} use something instead of index or use va
$set { "array.index.value" :"newvalue"} use something instead of index or use va

Time:01-12

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!

CodePudding user response:

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

CodePudding user response:

I found an answer online that works!

$set: {
      [`item.${item}.quantity`]: quantity  
    }
  • Related