How to Sum nodes in firebase firestore?

血红的双手。 提交于 2021-02-08 10:44:18

问题


I am making app for ordering pizza.

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();
  }

回答1:


There are basically two ways to sum up the value of a document field for all documents of a collection:

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/ 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.



来源:https://stackoverflow.com/questions/55311875/how-to-sum-nodes-in-firebase-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!