Firebase云功能汇总或汇总值

时间:2017-05-12 19:00:54

标签: firebase firebase-realtime-database google-cloud-functions

我一直试图通过新的firebase云功能来总结价格来提高总量

"Cart" : {
    "-Ksdasd50oR04q073k5" : {
      "ID" : 0.01,
      "price" : 20
    },
    "-KhOc0CGdsddihGB2N" : {
      "ID" : 001,,
      "price" : 20
    },

这是我的开始,

exports.cartadd = functions.database.ref('Cart/{uid}').onWrite(event => {

   let ref = admin.database().ref('Cart/{uid}');
   return ref.once('value').then(snapshot => {
      if (snapshot.hasChildren()) {
        var total= 0;
        snapshot.forEach(function(child) {

           total += snapshot.val().price;
        });
       console.log(total);
      }
  });

4 个答案:

答案 0 :(得分:3)

这应该这样做:

exports.cartadd = functions.database.ref('Cart').onWrite(event => {
      const snapshot = event.data;
      if (snapshot.hasChildren()) {
        var total= 0;
        snapshot.forEach(function(item) {
           total += item.child('price').val();
        });
        console.log(total);
      }
  });

答案 1 :(得分:1)

试试这个:

old_set = {'NYC', 'Ames', 'LA', 'Houston', '500',  '1000', '3000', 
                  'SanFrancisco', '300', '200', 'Detroit', 'Austin'}

new_set = {elem for elem in old_set if not elem.isdigit()}
print(new_set)
# output:
# {'NYC', 'Ames', 'LA', 'Houston', 'SanFrancisco', 'Detroit', 'Austin'}

答案 2 :(得分:0)

由于总需要更改,因此应该是var而不是const

更改

const total = 0;

var total = 0;

答案 3 :(得分:0)

total += child.val().price; // instead