【问题标题】:firebase / how i can to get a field from all doc's in firestore / javascriptfirebase /我如何从firestore / javascript中的所有文档中获取一个字段
【发布时间】:2019-03-18 23:20:58
【问题描述】:

结构 enter image description here

我需要从集合“values”中每个文档中的“Income”字段获取数据,并将它们写入数组以计算该数组元素的总和。

【问题讨论】:

  • 您对这项任务的哪一部分有疑问?您是否有任何无法按预期工作的代码要分享?
  • @DougStevenson 写入数组并计算

标签: javascript firebase google-cloud-firestore


【解决方案1】:

如果要对这些值求和,请执行以下操作。你不需要数组。

var totalIncome = 0;
db.collection("values").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        totalIncome += doc.data().Income;
    });
    console.log(totalIncome);
});

但是请注意,对于集合中的每个文档,都需要读取一个文档。如果您的 values 集合包含大量文档,您可以使用其他策略,例如在文档创建/删除时更新 totalIncome。

如果确实需要填充数组,请执行以下操作:

var totalIncomeArray = [];
db.collection("values").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        totalIncomeArray.push(doc.data().Income);
    });
    //Do whatever you want with the array: it contains all the Income values
});

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 2021-10-09
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多