聚合操作不返回任何具有mongoose模式的内容

9rbhqvlz  于 9个月前  发布在  Go
关注(0)|答案(2)|浏览(104)

主要目的是获取orders对象数组的总价。所以我使用了mongoDB聚合操作。我使用NoSQL booster检查查询,我可以得到totalPrice,但当我在应用程序中使用它时,它只是返回一个空数组[]。有人能找到我缺少的点吗

**下面显示了对象的示例。

"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
        }
    ]

字符串

下面是我使用的函数模式

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

avkwfej4

avkwfej41#

我想这就是你的目标:

export const GetTotalOrderPriceDB = async (userId: number) => {
    return await User.aggregate([
        {
            $match: {
                userId: userId
            }
        },
        {
            $unwind: "$orders"
        },
        {
            $group: {
                _id: null,
                totalPrice: {
                    $sum: {
                        "$multiply": [
                            "$orders.price",
                            "$orders.quantity"
                        ]
                    }
                }
            }
        },
        {
            $project: {
                _id: 0,
                totalPrice: 1
            }
        }
    ])
}

字符串
请参阅HERE以获取工作示例。

编辑:我刚刚注意到你的聚合实际上和我写的一样,但是你唯一的问题是,你的类型暗示了一个string,而根据你的示例文档,它应该是一个number

esbemjvw

esbemjvw2#

好,问题很简单,我发送“userId”并在管道的第一阶段使用.
注意:userId来自-

const userId = req.params.id

字符串
userId是一个字符串,因此它不能进入管道的下一阶段。因此显示空字符串。
应用:

const userId = Number(req.params.id)


或const userId = parseInt(req.params.id)
将userId数据类型更改为数字后,聚合工作正常。

相关问题