对 Firebase 数据库中的数据集取平均值 - Cloud Functions for Firebase

Taking the average of a data set in Firebase Database - Cloud Functions for Firebase

我正在创建一个允许用户从 1 到 5 对企业进行评分的应用程序。我试图找到要在我的应用程序中使用的评分的平均值。到目前为止,我目前只能使用此代码查看计数。

我正在努力弄清楚如何读取所有评级对象 (randomValue: Int)。我在想最好将它们存储在一个数组中。我是 Node 的新手,所以请原谅我。

我在 Cloud Functions for Firebase 文档中找不到任何关于此的内容。

评分存储如下:

我的代码:

exports.scoreOneAverage = functions.database.ref('/ratings_average/{business_uid}/Score_1/{random}')
.onWrite(event => {
  const collectionRef = event.data.ref.parent;
  const countRef = collectionRef.parent.child('count');

  // Return the promise from countRef.transaction() so our function
  // waits for this async event to complete before it exits.
  return countRef.transaction(current => {
    if (event.data.exists() && !event.data.previous.exists()) {
      return (current || 0) + 1;

    }
    else if (!event.data.exists() && event.data.previous.exists()) {
      return (current || 0) - 1;
    }
  }).then(() => {
    console.log('Counter updated.');
    List ratings = event.data.val();
    count = countRef.event.data.val();
    if( ratings === null ) {
          console.log('No ratings');
       }
       else {
          console.log("The average score is:" + count + ratings );
       }


  });
});

您要触发的云函数事件应稍作调整以使其正常工作。 B

来自docs on cloud functions

Path specifications match all writes that touch a path, including writes that happen anywhere below it. If you set the path for your function as /foo/bar, it matches writes at both of these locations:

/foo/bar
/foo/bar/baz/really/deep/path

所以基本上,解决这个问题的最佳方法可能是在这条路径上听写:/ratings_average/{business_uid}/Score_1

您可能还想利用奇妙的 lodash library - it has functions that will help you iterate over a javascript Object. Because your firebase database is structured as a series of nested json (with no notion of arrays), you need to traverse over objects to iterate on any collection of data, like the values at Score_1. Below, I'm using the handy lodash .forOwn() function, and lodash .size() 来获得我们在

上的平均分数

粗略地编码出来,平均函数如下所示:

// at the top of your file,
import _ from 'lodash';
exports.scoreOneAverage = functions.database.ref('/ratings_average/{business_uid}/Score_1')
  .onWrite(event => {
    const scores = event.data.val();
    const avgSum = 0;
    _.forOwn(scores, (scoreKey, scoreValue) => {
      avgSum += scoreValue;
    });
    const avg = avgSum / _.size(scores); // this is your average! Do with it what you like
  });