The main purpose is to get the total price of the orders array of objects. So I used mongoDB aggregation operation. I used NoSQL booster to check query there I can get the totalPrice but when I use it in the application it just return me an empty array []. Could anybody find which point I am missing
**The example of the object below is shown.
"userId": 1,
"username": "john_doe",
"password": "$2b$12$3fJyHTgM8QgU.q.tlpNVyOf.hJYfhVe7XPGCHm9Wq1RmexUZbUEeu",
"fullName": {
"firstName": "John",
"lastName": "Doe"
},
"age": 30,
"email": "[email protected]",
"isActive": true,
"hobbies": [
"reading",
"traveling"
],
"address": {
"street": "123 Main St",
"city": "Anytown",
"country": "USA"
},
"orders": [
{
"productName": "Product 1",
"price": 23.56,
"quantity": 2
},
{
"productName": "Product 2",
"price": 23.56,
"quantity": 5
}
]
Below is the function pattern I used
export const GetTotalOrderPriceDB = async (userId: string) => {
const result = await User.aggregate([
{
$match: { userId: userId },
},
{
$unwind: "$orders",
},
{
$group: {
_id: null,
totalPrice: {
$sum: { $multiply: ["$orders.price", "$orders.quantity"] },
},
},
},
{
$project: {
_id: 0,
totalPrice: 1,
},
},
]);
return result;
};
2
Answers
Well, The issue was very simple I sent "userId" as a string thus it can't go next pipeline. As a result empty string showed.
I think this is what you were aiming for:
See HERE for a working example.
Edit: I just noticed your aggregation was actually the same as the one I wrote but the only issue you had was that your are type hinting a
string
when it should be anumber
based on your sample document.