首页 > 解决方案 > 用 Firestore 计算收入总和

问题描述

我正在尝试serviceCost从 Firestore 计算总和。我设法获取了所有文档,但似乎查询只计算了给定月份输入的第一个成本。

代码:

firebase
  .firestore()
  .collection("users")
  .doc(uid)
  .collection("confirmed-appointments")
  .get()
  .then((querySnapshot) => {
      let serviceCostTotal = 0; //Will hold currentMonth Total Income.
      let monthNumber = 0;
      let array = [];
      querySnapshot.forEach((doc) => {
        monthNumber = parseInt(doc.data().month, 10);
        serviceCostTotal =
          serviceCostTotal + parseInt(doc.data().serviceCost, 10); //Calculate Total Month income using this formula
        array[monthNumber - 1] = serviceCostTotal; //Push the income of month X to array in X place
        serviceCostTotal = 0; // after pushing, initialize the sum to 0
      });

例如:我想计算第 10 个月的总服务成本。

Firestore 看起来像这样: 火库

在循环中,我试图获取serviceCost每个文档,并将其推送到数组 [monthNumber]。

问题是:如果我有 2 个文档,它们的值相同 "month: xx" ,则循环仅计算第一个文档的 serviceCost 值。这意味着如果我的总和需要为 6000,则只有 2500。

它只计算这个: 2

虽然我也有这个: 3

标签: javascriptreact-nativegoogle-cloud-firestore

解决方案


正如你所说,你已经在数组索引中有数据,所以你可以这样做

const querySnapshot = [{
  month: 10,
  serviceCost: 2500
}, {
  month: 10,
  serviceCost: 3500
}, {
  month: 11,
  serviceCost: 1000
}];

const array = [];
querySnapshot.forEach((doc) => {
  const monthNumber = parseInt(doc.month, 10);
  array[monthNumber - 1] = (array[monthNumber - 1] || 0) + parseInt(doc.serviceCost, 10);
});

console.log(array);

您基本上检查该月的该索引中是否有某些内容并将其添加或使用您计算的 serviceCostTotal


推荐阅读