findOneAndUpdate increment instead of update in mongoose
12,217
Solution 1
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
Solution 2
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.
Related videos on Youtube
Author by
Thian Kian Phin
Updated on June 18, 2022Comments
-
Thian Kian Phin almost 2 years
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); } }); }
-
abdulbarik over 7 yearsDid you try
$inc
?
-
-
Thian Kian Phin over 7 years$inc can use negative prefix? I thought there is something like $dec no?
-
abdulbarik over 7 years
$inc=1
mean increment by 1 and$inc=-1
mean decrement by 1 -
Medet Tleukabiluly over 7 years
{new: true}
not required -
abdulbarik over 7 yearsOhh my mistake I just updated his code with
$inc
removing it thanks, @MedetTleukabiluly -
Phil about 3 yearsOP asked for increase or decrease. With this, you can decrease if the value is negative, but then you could also get a count of sub 0 causing all sorts of other problems