Thian Kian Phin
Thian Kian Phin

Reputation: 931

findOneAndUpdate increment instead of update in mongoose

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

        }

Upvotes: 11

Views: 18744

Answers (2)

abdulbari
abdulbari

Reputation: 6242

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;    // increment by 1 every time
  if (!flag)
    flag = -1;     // decrement 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);
      }
    });
}

See the reference here for $inc

Upvotes: 18

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20108

Use $inc to increment particular field following way

update:

db.getCollection('noti').findOneAndUpdate(
   { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
   { 
      $inc: { count: 1 } 
   }, {new: true })

result:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 8.0,
    "color" : "green",
    "icon" : "circle",
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0,
    "views" : 1.0
}

Here, the count is incremented by 1 and before it was 7.

Upvotes: 3

Related Questions