在Firebase数据库中获取数据集的平均值

时间:2018-07-26 10:04:37

标签: javascript firebase firebase-realtime-database

我正在设计一个应用程序,但是对Javascript有点不了解。到目前为止,我有一个具有以下结构的Firebase实时数据库。 enter image description here

我想做的是每次添加/更新绿色区域时,从该绿色区域获取一个值(红色),以获取每个绿色对象和位置中保存的所有值的平均值它变成底部的棕色物体。

有人会对如何使用Javascript / Firebase函数完成此工作有任何想法吗?

JSON导出:

{
  "5Rz8DpU34PeXAcnriD6vEiPu7jk2" : {
    "UiWK7RkdeCbUte8g7naB9qp42qu1" : {
      "rating1" : 5
    },
    "average" : 0
  },
  "Fi43uP2LcbVLi2uFwUyCAp2uvSH2" : {
    "average" : 0
  },
  "UiWK7RkdeCbUte8g7naB9qp42qu1" : {
    "Fi43uP2LcbVLi2uFwUyCAp2uvSH2" : {
      "rating1" : 5,
      "rating2" : 5
    },
    "asdas" : {
      "rating1" : 2
    },
    "average" : 0
  },
  "gov4hRpDgDVhyVgsQrYJnn1rfeW2" : {
    "UiWK7RkdeCbUte8g7naB9qp42qu1" : {
      "rating1" : 5
    },
    "average" : 0
  }
}

2 个答案:

答案 0 :(得分:1)

以下Cloud Function代码应该可以解决问题:

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.database();

exports.average = functions.database
  .ref('/ratings/{blueId}/{greenId}')
  .onWrite((change, context) => {
    const blueId = context.params.blueId;
    const blueRef = db.ref('ratings/' + blueId);

    const blueAverageRef = db.ref('ratings/' + blueId + '/average');

    let totalSum = 0;
    let nbrOfElem = 0;

    return blueRef
      .once('value', function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          if (childSnapshot.val().val) {
            //console.log(childSnapshot.val());
            totalSum += childSnapshot.val().val;
            nbrOfElem++;
          }
        });
      })
      .then(() => {
        //console.log('totalSum: ' + totalSum);
        //console.log('nbrOfElem: ' + nbrOfElem);
        return blueAverageRef.transaction(function(average) {
          if (nbrOfElem > 0) {
            return { val: totalSum / nbrOfElem };
          } else {
            return 0;
          }
        });
      })
      .catch(error => {
        console.log(error);
      });
  });

请注意,它使用事务处理,请参见https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactionshttps://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction

数据库的结构应为:

-ratings
   -blueNode1
      -greenNode11
         -val:2  // <- red node in your picture
      -greenNode12
         -val:10
      -average   // <- red node in your picture
         -val:6
   -blueNode2
      -greenNode21
         -val:5
      -greenNode22
         -val:3
      -greenNode23
         -val:1
      -average
         -val:5

答案 1 :(得分:0)

会是这样的:

exports.detectGreenChanges = functions.database.ref('/requests/{blueId}/{greenId}').onWrite((change, context) => {
  const greenIdData = change.after.val();
  const blueId = context.params.blueId;
  const greenId = context.params.greenId;

  // Do whatever you want with the data and set it to where ever you want

});

看看this docs,它将帮助您将值设置回所需位置。

祝你好运!