How do I increment multiple indexes positionally?


#1

I have a collection representing robots holding an inventory of products in positional slots, which will be incremented and decremented.

{
  _id: "someid",
  name: "",
  inventory: [{
    productId: "productId1",
    count: 30
  }, {
    productId: "productId2",
    count: 56
  }, {
    // ... up to 55 slots.
  }]
}

I then have an API that will interact with this document on a PUT request. The request data will contain the index of the inventory to update and the number to decrement it by, eg:

[
  { "inventory": 3, "inc": -10 },  // remove 10 from robot.inventory[3]
  { "inventory": 54, "inc": -2 },  // remove 2 from robot.inventory[10]
]

I have the following code.

MachineApiV1.addRoute('/products', {
  authRequired: true,
  roleRequired: 'machine'
}, {
  put: function () {
    var data = this.request.data;
    var user = Users.findOne(this.request.headers['x-user-id']);
    Robots.update(user.profiles.robot, {
      $inc: { } // this is where I am lost.
    });
  }
});

I can’t quite think of a way to do it in a single update. How can I increment multiple arbitrary indexes in a mongo document?


#2

With my package vjau:mongo-extend :

var rob = Robots.findOne(user.profiles.robot);
rob.inventory[3].count -= 10;
rob.inventory[[54].count -=2 ;
Robots.extend(rob);

I have got 0 (zero !) installs for this package, and i don’t understand, i find it useful :no_good:


#3

Is writing it like the example here not working?