Explore the sibling data of a specific node with the power of Firebase Cloud Functions

I am currently working with Firebase real-time database and Firebase cloud functions (using Typescript). Below is the structure of my database nodes:

Orders Node:

orders
|- {Push ID}
    |--billing_id
    |--orders_id
    

Shippings Node:

shippings
|- {Push ID}
    |-- billing_id
    |-- user_id

My function monitors changes on the "orders" node and retrieves the value of the "billing_id".

Note: The billing_id matches the one stored in the "shippings" node. This billing_id will always exist in the "shippings" node.

Next, I aim to target the shippings node that contains the exact billing_id and fetch the user_id. Below is a shortened version of the code:

export const orderEmail = functions.database.ref('/orders/{pushId}')
.onCreate((snapshot,context)=>{
    const original = snapshot.val(); //Stores values from the newly created orders node
    const billing_id = original.billing_id; // Stores the billing_id from the newly created orders node

//I need assistance from this point onwards.
    let db = admin.database();
    let val1:any;
    db.ref(`/shippings/{pushId}/${billing_id}`).once("value") //What should I do next?
});

Edit 1:

I tried the solution recommended by Neelavar. Here are the warnings and errors I encountered while deploying the function:

WARNING: A:/HN/functions/src/index.ts:79:9 - Forbidden 'var' keyword, use 'let' or 'const' instead
WARNING: A:/HN/functions/src/index.ts:79:13 - Identifier 'db' is never reassigned; use 'const' instead of 'var'.
ERROR: A:/HN/functions/src/index.ts:86:24 - Shadowed name: 'snapshot'
WARNING: A:/HN/functions/src/index.ts:149:9 - Forbidden 'var' keyword, use 'let' or 'const' instead
WARNING: A:/HN/functions/src/index.ts:149:13 - Identifier 'options' is never reassigned; use 'const' instead of 'var'.

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ lint: `tslint --project tsconfig.json`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\RIYASREE'S_PC\AppData\Roaming\npm-cache\_logs\2020-10-15T14_18_07_047Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code2 

NOTE: Please inform me if you require any other information. Also, provide a comprehensive solution as I am new to both Firebase and Typescript.

Answer №1

Thanks to Neelavar's assistance and some code adjustments, I was able to successfully retrieve the desired value. The following is the updated code:

export const orderEmail = functions.database.ref('/orders/{pushId}')
.onCreate((snapshot,context)=>{
    const original = snapshot.val(); //Stores values from the newly created orders node

const billing_id = original.billing_id; // Stores the billing_id from the newly created orders node
        var db = admin.database();
        var val1:any;
       return db.ref(`/shippings`)
              .orderbyChild('billing_id')
              .equalTo(billing_id).once("value", snap:any => {
    const data = snap.val();
    const pushId = Object.keys(data)[0]; //Gets the Push Id
    const userId = data[pushId].user_id; // Gets the user_id
    console.log("User Id", userId)
        });
    });

Answer №2

After retrieving the billing_id using the onCreate trigger, the next step is to search the shippings node for the corresponding billing_id.

    db.ref(`/shippings`)
          .orderByChild('billing_id')
          .equalTo(billing_id).once("value", snapshot => {
           // Utilize the snapshot to access the shippings collection document
           // which now contains both billing_id and user_id matching the given billing_id

    });

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

The Ag Grid Cell Render feature is not available

I have been working on creating my own cell renderer by referring to this example https://www.ag-grid.com/javascript-data-grid/cell-rendering/, but I am running into an issue when using TypeScript. When I define a class that implements the ICellRenderer in ...

When deploying my Angular project, I am unable to access my files

I have been facing challenges while trying to deploy my web application with the frontend being Angular. The issue I am encountering is that I cannot access my JSON file located in the assets folder. Below is the function I am using to retrieve data from ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

How to generate an array within a TypeScript extension function

As I was working on creating an extension method using typeScript, the main goal was to establish a static or normal variable within the method. The ServiceCollector method was invoked three times in order to send and store data or objects in an array. B ...

Building a Model Class with redux-orm and TypeScriptCreating a new Model Class with

I've been successfully using redux-orm with JavaScript, however, I'm facing issues when trying to convert my code to TypeScript. Even though I have already implemented the render() method in my Folder Model Class, the TypeScript transpiler is sh ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

Issue with Angular authentication during login attempt

I am a beginner in Angular and I'm using this method to allow users to log into the system. loginuser(){ const user = { username: this.username, password: this.password }; this.Auth.loginUser(user).subscribe((res)=>{ ...

Combining Arrays of Items in Typescript

I am dealing with an array in Angular 14 that looks like this: [ { "parentItem": "WBP258R", "childItem": "WBP258R", "columnName": "Color", "oldValue": ...

Defining a TypeScript interface specifically tailored for an object containing arrow functions

I encountered an issue while trying to define an interface for the structure outlined below: interface JSONRecord { [propName: string]: any; } type ReturnType = (id: string|number, field: string, record: JSONRecord) => string export const formatDicti ...

Firebase deployment failures that initiate from a non-zero exit code

Hello developers, I'm facing an issue while trying to deploy a simple cloud function to the Firebase console. Everything seems to be working fine so far - from npm installation and configuration to other necessary steps. I have written a basic functi ...

Tips for correctly specifying the theme as a prop in the styled() function of Material UI using TypeScript

Currently, I am utilizing Material UI along with its styled function to customize components like so: const MyThemeComponent = styled("div")(({ theme }) => ` color: ${theme.palette.primary.contrastText}; background-color: ${theme.palette.primary.mai ...

What is the process for retrieving data from Firebase within a React Native application?

I am currently facing an issue with displaying data fetched from firebase. Here is how my data structure looks on firebase: {name: "sleep"} This is the only object stored in the database at the moment. I have implemented a ListView to show rows based on ...

Utilizing Google's Speech-To-Text for real-time data streaming in Angular

Utilizing the Google Speech-to-Text service through @google-cloud/speech library in my node.js Firebase functions has been helpful, but I am looking to implement it for streaming data which seems impossible with Firebase functions. As a result, I plan to ...

Menu Navigation: Sequentially Colored Badges for Navigation Items

Within the MainService.ts file, there is a function that can alter the color set in badgesColorSet. The json config already defines 3 colors and the goal is for these colors to change each time the website is refreshed - for example, changing from red to g ...

Retrieve the object attribute name through the request parameter in Express.js and Mongoose

Setting the Scene The issue at hand is my desire to access the attribute of an Object using the variable provided in the request. A GET /modify/:var request is initiated to alter the attribute of a saved document in MongoDB. In order to determine which at ...

Tips for creating a jasmine test scenario for a function executed within the ngOnInit lifecycle hook

I am finding it challenging to create a successful test case for the code snippet below. In my component.ts file id = 123456; data = []; constructor(private serv: ApiService){} ngOnInint(){ getData(id); } getData(id){ this.serv.getRequest(url+id) ...

Error TS2339: The "length" property cannot be found on the data type "never"

I'm a beginner in learning angular and typescript, and recently encountered this error: TS2339: Property 'length' does not exist on type 'never'. This issue arose in the following code snippet pertaining to "name.length". I aim ...

When using Observables in AngularFire2, the $ref property does not get captured

Recently, I started working with AngularFire2 (version 4.0.0-rc.1) and encountered a challenge that has me stuck: getWishlist$(): FirebaseListObservable<{}> { return <FirebaseListObservable<{}>>this.store.select(getFirebaseUID) ...

Using source maps with Typescript in Webpack (source maps not visible while using webpack-dev-server)

I am currently experimenting with Typescript in combination with Webpack, utilizing the 'awesome-typescript-loader' plugin. However, I am encountering an issue where the source maps are not displaying in the browser when running webpack-dev-serve ...

Leverage the JSON Web Token module within a Chrome extension

Currently in the process of developing a chrome extension but encountering an issue with loading the json web token node module in my Node.js setup. background-script.ts import jwt from 'jsonwebtoken'; // import * as jwt from '../node_mod ...