'How to loop through a firestore array and get a specific item

I am trying to develop a function to calculate the total price in my shopping cart. I have made it so that the "cost" value will be the "price" value times the "quantity" value. I am now trying to grab the "cost" values from all the different cart items and add them together to get the total price for my cart. How should I do this; I am not sure of how to loop through the different items.

Firestore Database



Solution 1:[1]

Firestore does not support aggregation queries as of now. You will have to fetch that document and calculate the total yourself from the Cart array.

Alternatively, you can store the total in a separate field in that document and keep it updated every time an item is added/remove from the cart using FieldValue.increment().

Solution 2:[2]

It looks like your Cart field is designed as a Firestore Array so when you read the specific cart doc you can simply do the following (example in JS):

firebase.firestore().collection('users').doc(userDocId).get()
  .then(doc=> {
    let total = doc.data().Cart.reduce((sum,item)=> sum += item.cost,0);
  });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj
Solution 2 Shai Ben-Tovim