如何在firebase firestore中求和节点? [英] How to Sum nodes in firebase firestore?
问题描述
我正在制作用于订购披萨的应用.
I am making app for ordering pizza.
就像你在图片上看到的那样,我想从每个文档中取出所有名为ukupno"的键值,然后将其求和以获得最终价格.
Like you see on image i want to take all key values named "ukupno" from each document and Sum it for final price.
这是我获取购物车数据的方式:
This is how i fetch cart data:
this.cartService.getCart(this.user.Uid).subscribe(res => {
this.cart = res.map(i => {
return {
...i.payload.doc.data(),
id: i.payload.doc.id
};
});
});
}
getCart(uid) {
return this.firestore
.collection("cart/")
.doc(uid)
.collection("/ubaceno")
.snapshotChanges();
}
推荐答案
对集合的所有文档求和一个文档字段的值,基本上有两种方法:
There are basically two ways to sum up the value of a document field for all documents of a collection:
1/查询整个集合,遍历结果(即 querySnapshot
),例如使用 forEach()
,并对循环中的所有字段值求和.要使用 angularfire2 做到这一点,您可能会使用 snapshotChanges()
.
1/ Query for the entire collection, loop over the result (i.e. the querySnapshot
), e.g. with forEach()
, and sum all the field values in the loop. To do that with angularfire2 you would probably use snapshotChanges()
.
但是,如果您的集合包含大量文档,这不是很有效,而且您的集合中的每个文档需要读取一个文档.
However, If your collection contains a lot of documents, this is not very efficient and moreover it will cost one document read per document in your collection.
2/使用一些分布式计数器保持所有文件的最新金额.要实现这种方法,您必须在每次创建/修改/删除 ubaceno
集合中的文档时更新计数器,添加或减去 ukupno
字段的值以/从柜台.
2/ Use some Distributed counters to keep an up-to-date sum for all your documents. To implement this approach, you have to update the counter each time you create/modify/delete a document in the ubaceno
collection, adding or subtracting the value of the ukupno
field to/from the counter.
您可以通过使用一组在创建/修改/删除时更新计数器的云函数来做到这一点,或者通过在前端的写入/修改/删除代码中集成计数器更新事务.
You could do that either by having a set of Cloud Functions that update the counters upon Creation/Modification/Deletion, or by integrating in your write/modify/delete code in your front end the transaction for the counter update.
这篇关于如何在firebase firestore中求和节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!