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);
}
});
}
As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
What is the difference between findOneAndUpdate and updateOne? findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).
You can update value by using { $inc: {views:1}} in mongoose.
Any findAndUpdateOne is atomic as long as it hit a single document. Thank you for your reply,i changed the question, i meant filter of update command not the findOneAndUpdate.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With