【发布时间】:2020-09-11 22:43:08
【问题描述】:
我在 MongoDB 和 nodejs 的多个集合中关注了这个 article on using transaction。经过多次尝试和失败,我发现事务仅适用于 ReplicaSet。所以我决定修改我的架构,以便我可以处理单个文档更新。
我的架构有点像这样,
// collection "products"
{
shop: 'ShopID1',
customer: ['CustomerID1', 'CustomerID2'],
products: [
{product: 'ProductID1', productCount: 10, customer: ['CustomerID1']} ....
]
}
因此,基本上,当customer 购买product 时,我想减少其productCount 并将它们添加到特定产品customer 数组和商店客户数组中。客户只有在产品数量 > 0 时才能购买产品。另一个限制是,客户只能从商店购买 ONE 产品。
我已经为此找到了以下更新查询,
db.collection('products').updateOne(
{ shop: shopName},
{
$inc: {'products.$[elem].productCount': -1},
$addToSet: {
'products.$[elem].customers': customerId,
'customers': customerId,
},
},
{
arrayFilters: [ {"elem.product": productId, "elem.productCount": {$gt: 0}} ],
},
);
此更新操作适用于有效场景(产品可用且客户尚未从商店购买任何东西)。但在无效场景下会失败。
我可以检查购买是否有效的一种方法是检查每个单独的更新是否导致修改。有什么方法可以检查 3 个更新操作中的每一个是否成功,如果没有以某种方式恢复更新?我也很感激处理这种情况的替代建议。谢谢。
注意:我正在使用 MongoDB 4.4 服务器并通过 NodeJS 使用 mongo 客户端 3.6 访问它
【问题讨论】: