其主要目的是获取对象的Orders数组的总价格.所以我使用了MongoDB聚合操作.我使用NoSQL Booster判断查询,在那里我可以得到totalPrice,但当我在应用程序中使用它时,它只有return me an empty array [].有谁能找出我漏掉了哪一点
**如下图所示.
"userId": 1,
"username": "john_doe",
"password": "$2b$12$3fJyHTgM8QgU.q.tlpNVyOf.hJYfhVe7XPGCHm9Wq1RmexUZbUEeu",
"fullName": {
"firstName": "John",
"lastName": "Doe"
},
"age": 30,
"email": "john.doe@example.com",
"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;
};