来自Firebase数据库的汇总值 [英] Aggregate values coming from firebase database

查看:63
本文介绍了来自Firebase数据库的汇总值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从Firebase中存储的一堆产品中计算出总价.由于在Firebase中每种产品将单独退回,我怎么知道什么时候可以完全计算出总数?

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?

例如:

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

如果我有12种产品,则只有从数据库中检索到所有这些产品后,才能返回总数,因此直到我确定所有产品都已获取后,我才可以使用变量total.

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.

推荐答案

我认为您应该重组数据以使其看起来像这样

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.

如果您只需要计算所有产品的价格(不确定原因),则可以收听child_added事件:

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

这篇关于来自Firebase数据库的汇总值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆