结构 enter image description here
我需要从集合“值”中每个文档中的“收入”字段获取数据,并将它们写入数组以计算该数组元素的总和。
最佳答案
如果您想对这些值求和,请执行以下操作。您不需要数组。
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
});
关于javascript - firebase/我如何从 firestore/javascript 中的所有文档中获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231494/