Home > Back-end >  How to loop through a firestore array and get a specific item
How to loop through a firestore array and get a specific item

Time:02-18

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

CodePudding user response:

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().

CodePudding user response:

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);
  });
  • Related