【问题标题】:How to sum all amount paid by users如何汇总用户支付的所有金额
【发布时间】:2021-07-18 17:03:20
【问题描述】:

我发现很难将订购商品的客户支付的所有金额加起来

订单架构

const orderschema = new Mongoose.Schema({
  created: { type: Date, default: Date.now() },
  amount: { type: Number, default: 0 }
  User: [{ type: Mongoose.Schema.ObjectId, ref: 'Users'}]
  ...
})

路线

Get('/total-amount', total-amount)

控制器

Exports.total-amount = () => {
  Order.find()...
}

我不知道要在这里添加什么才能得到所有客户的总金额。

使用 NodeJS 和 MongoDB。

感谢您的帮助

【问题讨论】:

    标签: node.js reactjs mongodb mongoose


    【解决方案1】:

    您可以在这样的聚合阶段使用$sum

    • 首先$group all(没有_id是对所有值进行分组)
    • 然后创建字段total,它是al amount 的总和。
    • 还有一个可选阶段,$project 仅输出 total 字段。
    db.order.aggregate({
      "$group": {
        "_id": null,
        "total": {
          "$sum": "$amount"
        }
      }
    },
    {
      "$project": {
        "_id": 0
      }
    })
    

    例如here

    要使用 nodeJS 和 Mongoose 添加到控制器中,您可以使用如下代码:

    Exports.total - amount = (req, res) => {
        Order.aggregate({
            "$group": {
                "_id": null,
                "total": {
                    "$sum": "$amount"
                }
            }
        }, {
            "$project": {
                "_id": 0
            }
        }).then(response => {
            res.status(200).send(response)
        }).catch(e => res.status(400).send())
    }
    

    请注意,操作是使用您的猫鼬模型完成的(在本例中为 Order)。您调用 aggregate 方法的方式与调用 find 方法的方式相同,例如:而不是做

    yourModel.find()
    

    yourModel.aggregate()
    

    响应将是:

    [
      {
        "total": 6
      }
    ]
    

    因此,即使您可以更新控制器以添加 if/else 块,如下所示:

    if(response[0].total)
      res.status(200).send(response[0].total)
    else
      res.status(404).send()
    

    【讨论】:

    • 谢谢@j.f 我想我还是想念它。我不熟悉聚合。如何将其添加到我的控制器。另外,我没有定义 db 而是将订单模型定义为 Order db.order.aggregate({ "$group": { "_id": null, "total": { "$sum": "$amount" } } }, { "$project": { "_id": 0 } })
    • 谢谢。有用。接受我真诚的感谢
    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2021-11-18
    • 2017-07-11
    • 2015-10-11
    • 2019-07-22
    相关资源
    最近更新 更多