2016-10-09 43 views
0

我有一個函數,假設加起來或減少信用。但是我的下面的代碼只是取代了信用值。貓鼬中有什麼捷徑可以增加或減少?否則我將不得不得到價值然後插入它,我認爲不是做它的方式。findOneAndUpdate增量而不是更新的貓鼬

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

     } 
+0

它取代了信用的價值,因爲這是你設置什麼。 '$ set:{credit:total_amount}'。你的代碼中沒有使用'topup_value'的地方。 –

+0

@凱我知道,我不是問爲什麼它取代我的價值。 –

+2

你試過'$ inc'嗎? – abdulbarik

回答

0

您可以將該值設置動態,並通過它查詢

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

+0

$ inc可以使用負數前綴嗎?我認爲有一些像十二月一樣沒有? –

+1

'$ inc = 1'表示增加1,'$ inc = -1'表示減1 1 – abdulbarik

+0

https://docs.mongodb.com/manual/reference/operator/update/inc/ – abdulbarik