Firebase Cloud Function performs a database retrieval operation

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);

});

Answer №1

Could you kindly test out the function provided below and share your feedback:

export const schoolUpdated = functions.database.ref('/buildings/{buildingId}/reviews/{buildingId}/rate').onWrite( (change, context) => {
    return Promise.all([admin.database().ref(`/buildings/${context.params.buildingId}/reviews`).once('value')]).then(r => {
      const allReviews = r[0];
      let sumScore = 0;
      let count = 0;
      allReviews.forEach(item => {
        sumScore += item.child('rate').val();
        count = count + 1;
      });
      let result = (sumScore / count);
      return change.after.ref.parent.parent.parent.child('finalResult').set(result);
    });
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch from manipulating the DOM to using Angular binding to update the td element with fresh information

When I click the edit button on a tr Element, the tdElement for the redirectUrl should become editable. By using the id of the tdElement and changing the contenteditable attribute to true, I can then use JQuery to retrieve the newly typed data. <tr ng- ...

Include TypeScript in a single component within an already established Vue project

I've been working on a large Vue project and I want to integrate TypeScript into it. However, every time I try to do so, I run into a lot of errors that take weeks to fix. Instead of going through that, I'd like to find a way to add TypeScript to ...

The header component does not update properly post-login

I am currently developing a web-app using Angular 8. Within my app, I have a header and login page. My goal is to update the header after a user logs in to display information about the current logged-in user. I attempted to achieve this using a BehaviorS ...

Exporting a Typescript interface from a restricted npm package

I'm working on an npm module using TypeScript that includes several interfaces. In the index.ts file, I export all of the classes and interfaces. I defined the interfaces as "interface dto {a:string;} export default dto". However, when I import the ...

Is it possible to confirm in Typescript if a given string key is valid for a specific type?

Apologies for the unclear wording of the question. Imagine having a data structure like this: type ExampleObject = { arr: Array<{x: number, y: Array<{z: string}>}>; obj: {[key: string]: number}; } I want to ensure that paths are valid - p ...

The culprit behind Angular 11 app error: Unidentified router outlet triggering 'No routes match' issue

In my Angular 11 application, I am utilizing a named router-outlet. The setup in my app.component.html file looks like this: <ng-container *ngIf="showGeneric"> <router-outlet name="general"> </router-o ...

custom validation for q-checkbox

As the title suggests, I am facing an issue with custom validation on my q-checkbox. The standard Quasar validation method is not working for me. Below are my checkboxes with custom DIVs for displaying error messages: <q-item style="padding-left: ...

The issue I'm facing with the mongoose schema.method is that the TypeScript error TS2339 is showing up, stating that the property 'myMethod' does not exist on type 'Model<MyModelI>'

I am looking to integrate mongoose with TypeScript and also want to enhance Model functionality by adding a new method. However, when I try to transpile the file using tsc, I encounter the following error: spec/db/models/match/matchModelSpec.ts(47,36): e ...

What could be the reason for the failed authentication HTTP request to Firebase resulting in error 400?

Ensuring the correctness of the API: ''' https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY] ''' source Verifying my API Key: https://i.sstatic.net/N4daZ.png The request made from a component: import { In ...

Using Typescript to set a custom timeout duration based on a dynamic variable within a for loop

My function includes a timeout that changes every 3 seconds: setActiveImage(promotions) { for (let i = 0; i <= promotions.length - 1; i++) { setTimeout(()=> { this.activeImage = 'http://myrul/public/Commercials/' + promo ...

Mapping Firebase UserInfo to a custom User model in Angular 7 using Angular Fire

I am a beginner with angular 7, and I am attempting to retrieve the current authenticated user from Firebase and map it to my custom User model (without using a constructor in User). The Firebase API structure: interface UserInfo { displayName: string ...

Having trouble transferring data using HttpClient in Angular 4 with a Symfony backend

Resolved using NelmioCorsBundle. I am currently utilizing angular 4.3.3 for the front end and Symfony3 for the backend, with the addition of FosRestBundle. When working with Angular, I primarily use HttpClient to handle data request and transmission. Da ...

Exploring Ways to Refresh the Appearance of Your Highchart Theme

My code allows me to switch between a light and dark theme for Highcharts, but the changes don't take effect until I refresh the page. Is there a way to update the theme without needing to refresh? ngAfterViewInit(){ Highcharts.setOptions(getOptio ...

Utilizing Angular 2 or TypeScript to Retrieve Visitor's Location

I initially began using ServerVariables["HTTP_CF_IPCOUNTRY"] on the backend server, but it's proving to be too slow. I'm looking for an Angular or TypeScript alternative to speed things up. ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

Using TypeScript to transform a tuple type into an object

When dealing with a tuple type like: [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string] there is a need to convert it ...

Building a custom Angular 6 pipe for generating a summary of a text snippet

Looking to create a pipe that limits the text box to only show the first 150 characters of the description. If the description is shorter than that, it should display the entire description followed by (...) Currently working on this: export class Tease ...

Steps for calling a function first and then canActivate():1. Begin by identifying the function you want

I have a unique condition in my AuthGuard code. If the resetpasss variable is not null, I want to navigate to the ResetPassIdComponent; otherwise, I want to navigate to the LoginFirstComponent. Here is my implementation of AuthGuard: export class AuthGua ...

The integration of react-color Saturation with @types/react-color is currently unavailable

In my quest to develop a customized color picker, I am utilizing the react-color library (^2.19.3) together with @types/react-color (^3.0.4). The issue arises when trying to import the Saturation component since it is not exported from the types in the ind ...