mongodb中的减量值 [英] Decrement value in mongodb

查看:42
本文介绍了mongodb中的减量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个购物应用程序.每个用户都有钱包. 结构就像:

I am creating a shopping application. Each user have wallet. Structure is like :

{ 
    "userName" : "Gandalf the Grey",
    "wallet" : 100,
    "orderHistory" : []
}

说此用户购买的商品价值50单位.有没有更好的方法,而不是通过findOne获取其钱包价值,然后进行减法并更新新的钱包价值?现在,我通过2种不同的操作来实现它

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); 
}

然后

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秒登录
发送“验证码”获取 | 15天全站免登陆