Using Firebase functions to save data to a database and then returning the object in response as JSON - how is it done?

Currently, I am utilizing a Firebase function to write data into the database. This function is triggered by an HTTP call, specifically a POST request. While I have successfully saved the data to the database, I have encountered difficulty returning the data in the proper format. The error message I'm receiving is as follows:

TypeError: snapshot.val is not a function

export const saveOrder = functions.https.onRequest(((request, response) => {

    if (request.method == "POST") {

        const data = JSON.stringify(request.body);
        let jsonData = data.replace(/\r?\n\t?/g, '');

        let object = {order: JSON.parse(jsonData), status: "pending"};

        return admin.database()
            .ref("orders")
            .push(object)
            .then(function (snapshot) {
                return response.send(200, snapshot.val());
            });
    } else {
        response.contentType("application/json");
        response.status(400).send('{"message":"Invalid method"}');
        return;
    }
}));

Answer №1

When using the .push() method, keep in mind that it does not give you a Snapshot data but rather a Reference.

If you want to retrieve the key of the new reference, you can do so like this:

.then((reference) => { return response.send(200, reference.key) });

In order to properly format the returned data, consider returning the object used in Firebase as follows:

return admin.database().ref("orders").push(object)
        .then(function(reference) {
            return response.send(200, {
                  key: reference.key,
                  data: object,
            });
        });

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

Unable to initialize the ng2-admin Angular2 Bootstrap template on a Go server due to a failed download attempt

Hello everyone, I am a newcomer to this forum and have limited experience with Angular2 and Golang. I am currently facing an issue as I want to experiment with a template on a Go server. To tackle this, I created a main.go file that includes the followin ...

Looking to incorporate form data into a nested object within Firebase using Angular2 - how can I accomplish this?

Trying to include user data in my Angular Fire object. This is how the database structure appears: Attempting to incorporate data into the roles object using the following code: Admin <label> Dealer</label&g ...

Clicking on a button to transfer items between pages (Ionic 2 + Angular 2)

I'm in the process of creating a recipe application and one feature I'd like to include is a shopping list page. On this page, users can click an "Add to Shopping List" button which will transfer the ingredients listed in a <ul> onto anothe ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

Troubleshooting auth error with Android and nativescript-plugin-firebase

I am currently utilizing this plugin in my application: https://github.com/EddyVerbruggen/nativescript-plugin-firebase Unfortunately, when using my real device on a 3G network, I encounter the following error: auth/network-request-failed Thrown if a netw ...

Implementing real-time updates in React-Big-Calendar by dynamically adding events from Firebase without the need for manual refreshing

I'm currently facing a challenge with React-Big-Calendar as I strive to achieve real-time population of newly added events. The code snippet below helps me achieve this goal, as events are promptly displayed on the calendar upon creation/modification/ ...

Using the useEffect hook with Redux-Toolkit dispatch causes an endless cycle of execution

Issue I am encountering an infinite loop problem when using useMutation from react-query to make post requests, retrieve user information from JSON, and then store it in my redux store using useEffect based on the status provided by the useMutation hook. ...

Tips for adjusting the size of icons in Ionic Framework v4 and Angular 7

The library ngx-skycons offers a variety of icons for use in projects. If you're interested, check out the demo here. I'm currently incorporating this icon library into an Ionic project that utilizes Angular. While the icons work perfectly, I&ap ...

Using an Angular Promise and Conditional Statement for Authentication Guard

I am trying to implement a guard that determines whether a user can access the login page, but I suspect my approach is flawed due to my use of Promises. Here is the relevant code snippet: canActivate(): boolean | Observable<boolean> | Promise<b ...

An issue occurred at line 2, character 16 in the generateReport.service.ts file: TypeScript error TS2580 - The term 'require' is not recognized

I have a requirement in my app to generate a report in the form of a Word document with just a click of a button. Previously, I successfully accomplished this using the "officeGen" module in a separate project. You can find more information about the modul ...

Ways to retrieve the most recent update of a specialized typing software

When attempting to run typings install in a sample project with the below typings.js file, I received a warning. How can we determine the latest version number and what does the number after the + symbol signify? { "globalDependencies": { "core-js ...

Utilizing React Redux and TypeScript to link a component with OwnProps in the ReactRedux template project of .NET Core 2.0

You can find the source code here. After some troubleshooting, I managed to get my code 99% working. However, despite everything running smoothly after compilation, I encountered a warning about the count property being missing when using it in a parent c ...

Create a unique TypeScript constant to be mocked in each Jest test

Having difficulty mocking a constant with Jest on a per test basis. Currently, my mock is "static" and cannot be customized for each test individually. Code: // allowList.ts export const ALLOW_LIST = { '1234': true }; // listUtil.ts import { ...

Transform the object into a function that returns the object while still maintaining the casting

I have this item: const five: { quantity: number } = { quantity: 5, } I would like to transform it into a function that yields the same item, like this: const five = () => ({quantity: 5}) Is there a way for me to reuse the casting to ensure the re ...

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...

Perform an action after the Ngx Bootstrap modal has been hidden

My modal features a login button: <button type="button" (click)="save()" class="btn btn-primary"> login </button> Upon clicking the button, my desired outcome is to: first hide the modal, and second navigate to another route. However, ...

What is the process for assigning the same type as one of the type members?

Consider the following code snippet: interface DbType { id: string, } interface RowType extends DbType { name: string } class MyDB<T extends DbType> { insert(item: T) { } delete(id: [typeof id]) { } } Let's say I create a n ...

What is the method for including a dynamic image within the 'startAdornment' of MUI's Autocomplete component?

I'm currently utilizing MUI's autocomplete component to showcase some of my objects as recommendations. Everything is functioning correctly, however, I am attempting to include an avatar as a start adornment within the textfield (inside renderInp ...

Exploring Angular 2: Integrating External Libraries

As a beginner in Angular and Angular 2, I am interested in incorporating an external library into my project. The library can be found at the following link: In order to use this library, I added the following line to my index.html file before angular: & ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...