我正在创建一个购物应用程序。每个用户都有钱包。结构如下:
{
"userName" : "Gandalf the Grey",
"wallet" : 100,
"orderHistory" : []
}
假设这个用户购买了50个单位的东西。有没有更好的方法而不是使用findOne获取其钱包值,然后进行减法并更新新的钱包值?现在,我正在使用两种不同的操作来制作它
dbo.collection('users').findOne({'userName': controller.userName})
.then(function(doc) {
updateWallet(doc);
}
然后
let newWalletBalance = doc.wallet - product.cost;
dbo.collection('users').updateOne(
{'userName':controller.userName},
{ $set: {wallet: newWalletBalance } }
);
是否可以将它们合并为一个?
您可以使用$inc
运算符
db.collection('users').updateOne(
{ 'userName': controller.userName },
{ '$inc': { 'wallet': -product.cost } }
)