I attempted to develop a basic billing application. In this application, I am required to track the opening quantity of each product in my store, as well as sales and purchases linked to specific product IDs. To achieve this, I need to calculate the current stock for each product in my Products collection. You can check out the implementation on this Playground.
Here is an overview of the data stored in the collections:
[
{
"_id": ObjectId("6499d7eb72fb2552774c9f80"),
"name": "Product 1",
"openingStock": 10
},
{
"_id": ObjectId("6499d81a72fb2552774c9f82"),
"name": "Product 2",
"openingStock": 10
},
{
"_id": ObjectId("6499d83d72fb2552774c9f84"),
"name": "Product 3",
"openingStock": 20
},
{
"_id": ObjectId("6499d86e72fb2552774c9f86"),
"name": "Product 4",
"openingStock": 15
}
]
Data from Sales Collection:
[
{
"_id": ObjectId("64a559f68d79acbc66d96fdf"),
"products": [
{
"product": ObjectId("6499d7eb72fb2552774c9f80"),
"qty": 3
},
{
"product": ObjectId("6499d83d72fb2552774c9f84"),
"qty": 3
}
]
},
{
"_id": ObjectId("64a559da8d79acbc66d96fde"),
"products": [
{
"product": ObjectId("6499d7eb72fb2552774c9f80"),
"qty": 3
},
{
"product": ObjectId("6499d83d72fb2552774c9f84"),
"qty": 1.5
}
]
}
]
Data from Purchase Collection:
[
{
"_id": ObjectId("64a5b540ffcbb3b942ccaae8"),
"products": [
{
"product": ObjectId("6499d81a72fb2552774c9f82"),
"qty": 2
},
{
"product": ObjectId("6499d7eb72fb2552774c9f80"),
"qty": 3.3
}
]
}
]
The expected result should look like the following:
[
{
"_id": ObjectId("6499d7eb72fb2552774c9f80"),
"name": "Product 1",
"stock": 7.3
},
{
"_id": ObjectId("6499d81a72fb2552774c9f82"),
"name": "Product 2",
"stock": 12
},
{
"_id": ObjectId("6499d83d72fb2552774c9f84"),
"name": "Product 3",
"stock": 15.5
},
{
"_id": ObjectId("6499d86e72fb2552774c9f86"),
"name": "Product 4",
"stock": 15
}
]
If you have any insights or solutions, please share them with me. Thank you.