findOneAndUpdate increment instead of update in mongoose
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);
}
});
}
See the reference here for $inc
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.