Decrement value in mongodb

末鹿安然 提交于 2020-05-09 06:33:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!