问题
I am creating a shopping application. Each user have wallet. Structure is like :
{
"userName" : "Gandalf the Grey",
"wallet" : 100,
"orderHistory" : []
}
Say this user buys something that costs 50 units. Is there a better way Instead of fetching its wallet value with findOne, then making substraction and updating new wallet value? Right now, I am making it with 2 different operations that looks like
dbo.collection('users').findOne({'userName': controller.userName})
.then(function(doc) {
updateWallet(doc);
}
then
let newWalletBalance = doc.wallet - product.cost;
dbo.collection('users').updateOne(
{'userName':controller.userName},
{ $set: {wallet: newWalletBalance } }
);
Is it possible to merge them into one?
回答1:
You can use $inc operator
db.collection('users').updateOne(
{ 'userName': controller.userName },
{ '$inc': { 'wallet': -product.cost } }
)
来源:https://stackoverflow.com/questions/55679123/decrement-value-in-mongodb