'Mongoose, conditional atmoic update
Using mongoose, I want to decrease the value of count by one, unless the value is already 0. I also need this operation to be atomic, so I'm using findOneAndUpdate. I've tried the following code, however have had no luck. Any recommendations?
Item.findOneAndUpdate({
_id : req.query.item_id,
user : req.user._id
},{
$inc: {
count : {
$cond: {
if: { count : {$gt : 0} },
then: -1,
else: 0
}
}
}
})
Provides the following error message:
MongoServerError: Cannot increment with non-numeric argument: {count: { $cond: { if: { count: { $gt: 0 } }, then: -1, else: 0 } }}
Solution 1:[1]
My solution to this problem was a workaround, instead of conditionally $inc count, I just filter to only return results with a count greater than 0.
Item.findOneAndUpdate({
_id : req.query.item_id,
user : req.user._id,
count : {$gt : 0}
},{
$inc: { count : -1}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ian Wise |
