node.jsmongodbexpressmongoosecrud

Aggregate operation is not returning anything with mongoose schema


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;
};

Solution

  • Well, The issue was very simple I sent "userId" and used that in the first stage of the pipeline.

    Note: userId comes from-

    const userId = req.params.id
    

    The userId is a string there thus it can't go next stage of the pipeline. As a result empty string showed.

    Applied:

    const userId = Number(req.params.id) 
    

    Or const userId = parseInt(req.params.id)

    After changing the userId data type into numbers the aggregation worked.