我有一个集合代表机器人在位置槽中持有产品库存,这些产品将递增和递减。
{
_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 文档中递增多个任意索引?
最佳答案
MongoDB 让它变得非常简单 - 只需指定要更新的子文档数组中的位置:
Robots.update(user.profiles.robot, {
$inc: {
'inventory.3.count': -10,
'inventory.54.count': -2
}
});
关于javascript - 在mongodb中同时并按位置递减多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348966/