2015-07-10 42 views
2

我有一個集合,它代表機器人在位置插槽中持有產品庫存,這些庫存將會遞增和遞減。在mongodb中同時遞減多個值

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

然後,我有一個API將與PUT請求上的此文檔進行交互。請求數據將包含inventory的索引來更新,並通過遞減它的數量,例如:

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

我有以下代碼。

// robots submit to this api to keep their products up to date 
MachineApiV1.addRoute('/products', { 
    authRequired: true, 
    roleRequired: 'machine' 
}, { 
    put: function() { 
    // omit process to get data from above 
    var user = Users.findOne(this.request.headers['x-user-id']); 
    Robots.update(user.profiles.robot, { 
     $inc: { } // this is where I am lost. 
    }); 
    } 
}); 

我不能完全想到在單次更新中做到這一點的方法。如何在mongo文檔中增加多個任意索引?

+0

唉,我不使用貓鼬(使用流星) – corvid

回答

1

的MongoDB使得它可以很簡單 - 只需指定子文件的陣列中的位置要更新:

Robots.update(user.profiles.robot, { 
    $inc: { 
    'inventory.3.count': -10, 
    'inventory.54.count': -2 
    } 
});