Aggregate Values Coming From Firebase Database
I have to calculate the total price from a bunch of products stored in firebase. Since in firebase each product will be returned separately, how can I know when the total is comple
Solution 1:
I think you should restructure your data to look something like this
products-product1-product2-product3.....selected_productsuser1:-products_list:-product2:true-pruduct3:true-product6:true-total_price:140
This way, you won't have to worry about calculating the prices on the client-side. Just add up the prices as the user selects the products.
If that's not the use case (a user selecting products), meaning that you need the total price for other reasons, then this approach won't be helpful.
Edit:
If all you need is to calculate the price of all products(not sure why), you can listen to child_added events:
var totalPrice = 0;
firebaseApp.database().ref(`/products/`).on('child_added', function(snapshot){
var product = snapshot.val();
totalPrice += product.price;
})
When all of this is done, you should have a variable with the price value of all products combined.
Similarly, you could achieve the same result with a once('value') call.
firebaseApp.database().ref(`/products/`).once('value', function(snapshot){
snapshot.forEach(function(productSnapshot){
totalPrice += productSnapshot.val().price;
})
})
Post a Comment for "Aggregate Values Coming From Firebase Database"