javascript - 用 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 个月的总服务成本。
在循环中,我试图获取serviceCost
每个文档,并将其推送到数组 [monthNumber]。
问题是:如果我有 2 个文档,它们的值相同 "month: xx" ,则循环仅计算第一个文档的 serviceCost 值。这意味着如果我的总和需要为 6000,则只有 2500。
解决方案
正如你所说,你已经在数组索引中有数据,所以你可以这样做
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
推荐阅读
- maven - Gitlab CI/CD 运行器:找不到 mvn 命令
- javascript - 如何从 Telerik Rad 电子表格中删除控件
- android - 如何使用 Retrofit 2 发送一组图像以及每个图像的数据?
- python - Python Plotly:使用下拉菜单在等值线图和散点图之间切换
- php - 使用 ON DUPLICATE UPDATE 时 PDO 避免出现间隙
- overwrite - Sylius 覆盖安全控制器
- apache-camel - 如何销毁camel组件及对应的Endpoint、Producer和Consumer?
- react-native - 如何在 GraphQl 和 Neo4js 中处理响应
- javascript - Javascript循环遍历许多对象的对象
- swift4 - 如何在swift 4中将base64编码的字符串解码为UIimage?