findOneAndUpdate 增量而不是猫鼬中的更新 [英] findOneAndUpdate increment instead of update in mongoose
本文介绍了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
这篇关于findOneAndUpdate 增量而不是猫鼬中的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文