findOneAndUpdate 增量而不是猫鼬中的更新
问题描述:
我有一个函数可以增加或减少信用.但我下面的代码只是替换信用值.猫鼬有什么捷径可以增加或减少吗?否则我将不得不获取值然后将其插入,我认为这不是这样做的方法.
I have a function that suppose to add up or decrease credit. But my below code merely replace the credit value. Is there any shortcut in mongoose that I can do increment or decrement? else I will have to get the value then insert it back, which I think is not the way to do it.
function update_total_credit(total_amount, topup_value){
User.findOneAndUpdate(
{email: user_email},
{$set:{credit:total_amount}},
{new: true},
function(err, response){
if(err){
res.json(0);
}else{
res.json(response.credit);
}
});
}
答
可以动态设置值并在查询中传递
You can set the value dynamic and pass it in the query
function update_total_credit(total_amount, topup_value) {
//The flag value means your breakpoint where you decide which value should go in query, you can change on your requirement basis
var flag = 1;//increament by 1 every time
if (!flag)
flag = -1;//decreament by 1 every time
User.findOneAndUpdate({
email: user_email
}, {
$inc: {
credit: flag
}
},
function(err, response) {
if (err) {
res.json(0);
} else {
res.json(response.credit);
}
});
}
请参阅此处的参考 $inc