Aggregate values coming from firebase database

∥☆過路亽.° 提交于 2019-12-25 09:25:01

问题


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 completely calculated?

For example:

var total = 0;
firebaseApp.database().ref('/products/').once('value')
.then(function(snapshot) {
    var product = snapshot.val();
    total += product.price;
});

If I have 12 products, the total can only be returned once all those products are retrieved from the database so it's not possible for me to use the variable total until I'm sure all the products are fetched.


回答1:


I think you should restructure your data to look something like this

products
    -product1
    -product2
    -product3
     .....

selected_products
    user1:
       -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;  
    })
})


来源:https://stackoverflow.com/questions/41568734/aggregate-values-coming-from-firebase-database

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