Search code examples
javascriptnode.jsmongodbmongoose

How to increment value in an object, MongoDB


I am trying to increment a value in an object by 1, but I cannot seem to figure it out. I have a mongoose Schema set up as follows:

const userSchema = new Schema({
  _id: Schema.Types.ObjectId,
  userId: String,
  items: Object
});

Which stores data as follows:

items: {
  "1234": 1,
  "5678": 4
}

Where 1234 and 5678 are item IDs, and 1, 4 are the quanitity of that item the user has. As an example, I need to increment "1234": 1 by 1, to return "1234": 2, and leaving "5678" : 4 unchanged. I have tried:

let newItem = "1234";
let userProfile = await User.findOneAndUpdate({ 
  userId: userID
}, {
  $inc: {
    items: {
      newItem: 1
    }
  }
});

Which returns an error: The field 'items' must be an array but is of type object.

I have also tried:

  $inc: {
    "items":  {
      newItem: 1
    }
  }

Which returns: Cannot increment with non-numeric argument: {items: { newItem: 1 }}, and:

$inc: {
  `items.${newItem}`: 1 
}

Which returns

`items.${newItem}`: 1 
^^^^^^^^^
SyntaxError: Unexpected template string

Solution

  • Figured it out. To use a variable in the keyname, wrap a template in []

    $inc: {
      [`items.${newItem}`]: 1 
    }