Below is my code to update currentQuantity of stock document.
for an example;
Instance 1
previously requested stock qty = 5;
newly requested stock qty = 10
therefore diff_qty = 10-5 = 5;
Instance 2
previously requested stock qty = 5;
newly requested stock qty = 3
therefore diff_qty = 3- 5 = (-)2;
Instance 3
previously requested stock qty = 5;
newly requested stock qty = 5
therefore diff_qty = 5- 5 = 0;
I have written the code to cover all these instances inside $switch. See below.
await Stock.updateOne(
{
_id: mongoose.Types.ObjectId(el.stockId),
agency,
},
[
{
$set: {
currentQuantity: {
$add: [
'$currentQuantity',
{
$switch: {
branches: [
{
case: { $gt: [diff_qty, 0] },
then: {
$cond: [
{ $gte: ['$currentQuantity', diff_qty] },
-diff_qty,
0,
],
},
},
{
case: { $lt: [diff_qty, 0] },
then: { $abs: diff_qty },
},
],
default: 0,
},
},
],
},
},
},
{
$set: {
unitQuantity: {
$mod: ['$currentQuantity', el.units],
},
},
},
{
$set: {
caseQuantity: {
$floor: {
$divide: ['$currentQuantity', el.units],
},
},
},
},
],
{ session: session }
);
In any of the cases my stock will be updated.
As in if my currentQty = 10;
Instance 1
previously requested stock qty = 5;
newly requested stock qty = 10
therefore diff_qty = 10-5 = 5; // Request 5 more items from the stock
then currentQty = 10 - 5 = 5;
Instance 2
previously requested stock qty = 5;
newly requested stock qty = 3
therefore diff_qty = 3- 5 = (-)2; // 2 items are returned back to the warehouse so it needs to be added back to stock
then currentQty = 10 + 2 = 2;
Instance 3
previously requested stock qty = 5;
newly requested stock qty = 5
therefore diff_qty = 5- 5 = 0;
then currentQty = 10 + 0 = 10;
I want to identify the update which happened in Instance 1, and Instance 2.
But not Instance 3 even thought it was updated from currentQty 10 => 10 and there is no effect in that update.
Is there any way i could achieve this in the aggregate pipeline itself? Your thoughts would be really helpful
Cheers