I've been working on a Firebase cloud function that needs to calculate an average based on a property of each node.
Here is the structure of my Real Time Database:
-- Buildings
- BuildingID1
- finalResult: 6.5
- Reviews
-ReviewID1
- rate : 10
-ReviewID2
- rate : 3
- BuildingID
- finalResult: 1.5
- Reviews
-ReviewID
- rate : 2
-ReviewID
- rate : 1
My goal is to update the 'finalResult' property by calculating the average grade from all the Reviews within that building whenever a Review is added, removed, or updated.
Currently, I'm having trouble figuring out how to query the database to retrieve the 'rate' property from the other nodes. Can anyone provide guidance on this?
export const schoolUpdated = functions.database.ref('/buildings/{buildingId}/reviews/{buildingId}/rate').onWrite( (change, context) => {
const data = change.after.val();
// ** Calculate the result by fetching and summing grades from all reviews **/
return change.after.ref.parent.parent.parent.child('finalResult').set(result);
});