Skip to content Skip to sidebar Skip to footer

I Want To Get The Average My Firebase Data

I want to average the related values ​​when the data in the FireBase is updated. I am using Firebase functions and can not load data. I can change the data I want when the even

Solution 1:

I'm not sure why you can't calculate the average, but a simpler version of your code would be:

exports.taverage = functions.database.ref('/User/tsetUser/monthQuit/{pushId}')
.onCreate((snapshot, context) => {
    return admin.database().ref('/User/tsetUser/monthQuit/{pushId}').once('value')
    .then(function(snapshot) {
        letsum=0;
        snapshot.forEach(child => {
            sum = sum + child.val();
        })
        let avg = sum / snapshot.numChildren();

        return admin.database().ref('/User/tsetUser/inform/standardQuit').set(avg);
    });
});

The biggest differences:

  • This code returns promises from both the top-level, and the nested then(). This is needed so Cloud Functions knows when your code is done, and it can thus stop billing you (and potentially shut down the container).

  • We simply add the value of each child to the sum, since you weren't using the array in any other way. Note that the child.val() depends on your data structure, which you didn't share. So if it fails there, you'll need to update how you get the exact value (or share you data structure with us).

  • The code actually calculates the average by dividing the sum by the number of child nodes.


Consider using a moving average

One thing to keep in mind is that you're now reading all nodes every time one node gets added. This operation will get more and more expensive as nodes are added. Consider if you can use a moving average, which wouldn't require all child nodes, but merely the current average and the new child node. The value will be an approximate average where more recent value typically have more weight, and is much cheaper to calculate:

exports.taverage = functions.database.ref('/User/tsetUser/monthQuit/{pushId}')
.onCreate((snapshot, context) => {
  return admin.database().ref('/User/tsetUser/inform/standardQuit').transaction(function(avg) {
    if (!avg) avg = 0;
    return (15.0 * avg + snapshot.val()) / 16.0;
  });
});

Post a Comment for "I Want To Get The Average My Firebase Data"