其主要目的是获取对象的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;
};

推荐答案

问题很简单,我把"userid"作为一个字符串发送,所以它不能进入下一个管道.结果显示为空字符串.

Node.js相关问答推荐

使用OpenAI API时遇到问题

promise 所有映射或反对

如何解决无法获得本地颁发者证书的问题

如何在不丢失其他键的情况下解开子文档数组,然后反转该过程?

如何在Angular jest测试中调用Nodejs的垃圾收集? node v20的测试速度慢且内存泄漏

使用AWS SDK for JavaScript V3将图像从node.js上传到s3 bucket

Puppeteer 的 BrowserFetcher 发生了什么?

表达 js 错误处理程序在第一个之后被忽略

使用 create-expo-app 时如何更改 webpack-config.js 中的哈希函数?

将 AllowDiskUse true 添加到 node.js 中的 MongoDB 聚合?

错误:无法检测到网络(event="noNetwork",code=NETWORK_ERROR,version=providers/5.6.8)

JavaScript & Node - 将图像文件保存到服务器但无法查看

Azure Function 在 2022 年 4 月 26 日禁用将用户字段设置为 HTTP 请求对象

使用新react 18.0.0 的 create-react-app my-app redux 错误

Node.js 支持 =>(箭头函数)

Puppeteer:如何提交表单?

响应分块时获取整个响应正文?

找不到在 docker compose 环境中运行的 node js 应用程序的模块

`return function *(){...}` 是什么意思?

Mongoose - 验证邮箱语法