Obtain the key of the parent node from the Realtime Database using Firebase Cloud Functions

I'm facing an issue trying to retrieve the parent node key from the snapshot. The function below successfully returns the correct node data when I print snapshot.val(), indicating that the problem is not with the query itself. However, I am struggling to find a way to extract the key of the returned snapshot.

/games
   |--{game_id} ==> need to fetch this ID
         |---"alias":"123456" ==> retrieved from the queried snapshot
         |---"players":...
         |..... // other children of game_id

Below is the cloud function code:

export const getGameIDFromCode = functions.https.onCall((data, context) => {

    if (context.auth == null) {
        throw new functions.https.HttpsError('permission-denied', 'You are not authorized to use this feature');
    }

    const code = data.code;
    const gamesRef = db.ref("/games");
    return gamesRef.orderByChild("alias").equalTo(code).once("value").then(snapshot => {

        if (snapshot.ref.parent != null) {
            // Attempted methods like snapshot.key and snapshot.ref.key without success
            return snapshot.ref.parent.key;
        } else {
            return "Unable to locate game_id for the provided code";
        }


    }).catch(error => {
        return error;
    });


});


Answer №1

Modified the code as follows for it to function correctly:

gamesRef.orderByChild("alias").equalTo(code).limitToLast(1).once("value").then(snapshot => {

        let gameKey;

        snapshot.forEach(child => {
            gameKey = child.key;
        })

        return gameKey;

    }).catch(error => {
        return error;
    });

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

Intellisense for dispatch types in Redux Toolkit

After following the documentation for redux toolkit with typescript, I implemented my own useDispatch hook as shown below export const useAppDispatch = () => useDispatch<AppDispatch>() and used it in components like this const dispatch = useAppDi ...

Instructions for adding a name to a string based on certain conditions

I am attempting to prepend a company name to a card number using the code provided. The challenge I am facing is incorporating the specific rules for each company as conditions for an if statement. Although I acknowledge that my current approach with the ...

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

Error in Angular: The use of decorators in this context is not allowed.ts(1206)

In my current project using Angular 17 and PrimeNG 17, I am implementing a theme switching feature. I have been following a tutorial from the Primeng documentation at this link: https://www.youtube.com/watch?v=5VOuUdDXRsE&embeds_referring_euri=https%3A ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

Eliminating the "undefined" error in TypeScript within a React application

Having recently dived into TypeScript configuration, I encountered an issue when coding and tried to resolve it by encapsulating the code block in an if statement checking for usersData to eliminate the "Object is possibly undefined" errors. However, upon ...

Angular Reactive Forms: Enhancing User Interaction

Currently, I am delving into reactive forms and encountering difficulty in pinpointing the form control that has been updated or changed from the UI. When using the valueChanges() method, it retrieves the entire form instead of the specific form control th ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Why isn't the input value being transmitted to the child component in Angular 5?

I have a dashboard and skills components and I am trying to pass the type from dashboard to be used in skills. However, I am encountering an error stating it is undefined. Dashboard Component: export class DashboardComponent implements OnInit { type: s ...

Typescript: Using axios to retrieve POST response beyond function boundaries

I've been working on a Typescript function that is supposed to generate and return a token value. Everything seems to be functioning properly, but I'm encountering an issue where the token value is only being logged to the console instead of bein ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

Check if a form field's value is lower than another in Angular reactive forms

In the form, I have a field called LDC along with two other fields named limit1 and limit2. My goal is to display an error message if either limit1 or limit2 exceeds the value of LDC, or if the sum of limit1 and limit2 surpasses LDC. I attempted to creat ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...

Guide to integrating global interfaces into your Nuxt project

Recently diving into the world of Nuxt 3, I've encountered a challenge while exploring TypeScript functionalities. My current goal is to create a versatile NavBar featuring multiple buttons with unique links. To achieve this, I aimed to establish an ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

Encountering an issue with Next.js, Typescript, and mongoose when attempting to use `let cached = global.mongoose

I attempted to create a cached mongoose connection for my Next.js + Typescript application, but the code I used was: let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } The use of global.mongoose res ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

Is there a way to trigger the function specifically when returning to the previous screen from the next screen within a react native application?

To activate the API, it is required that we only trigger the call when transitioning from the next screen back to the previous screen. The API should not be invoked on the initial visit to the screen in react native. ...

The 'Observable<ArrayBuffer>' type cannot be assigned to the 'Observable<HttpResponse<User>>' type

Hello there, I am currently facing an issue with setting up an authentication service. Whenever I try to login, I keep getting this error message: Type 'Observable' is not assignable to type 'Observable<HttpResponse>'. Type &a ...