问题
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