Real-time database logging triggered by Firebase user authentication

exports.setupDefaultPullups = functions.auth.user()
    .onCreate(
        async (user) => {
            const dbRef= functions.database.ref;
            let vl= await (dbRef.once('value').then( (snapshot) => {
                return snapshot.ref.child('userInfo/'+user.uid).set(18);
            }));
            return vl;
        }
    );

I have been working on creating a trigger to initialize settings for new users in Firebase. Unfortunately, the code above is not functioning as expected. Can anyone identify what might be causing this issue? Essentially, when a new user registers, I want to automatically set their "defaultPullUps" property to 18 using the specified path.

UPDATE: Apologies for the lack of detail initially. The problem with the "async" keyword has been resolved by updating the node.js engine. However, I am encountering different error messages depending on how I modify the code. At times, it indicates that "... is not a function".

UPDATE': Despite acknowledging the shortcomings of my question, there is valuable information within it: the online documentation for Firebase authentication triggers lacks guidance on accessing the "main" database https://firebase.google.com/docs/functions/auth-events

UPDATE'': Below is the full error message:

TypeError: Cannot read property 'child' of undefined
at exports.setupDefaultPullups.functions.auth.user.onCreate.user (/srv/index.js:15:36)
at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at /worker/worker.js:756:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)

Answer №1

This statement lacks coherence:

const dbRef= functions.database.ref;

If you are aiming to utilize the Firebase Realtime Database within a Cloud Function triggered by another source (such as Firebase Authentication), you should employ the Firebase Admin SDK.

To see an illustration of this, refer to the Initialize Firebase SDK for Cloud Functions portion of the Get started with Cloud Functions documentation. Specifically, you will have to import and initialize it as follows:

// The Cloud Functions for Firebase SDK to establish Cloud Functions and configure triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK for accessing the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

You can then access the database from your function using:

const dbRef= admin.database().ref();

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

ui-jq flot graph with lazy loading

I am working with this HTML code: <div id="test" ui-jq="plot" ui-options=" [ { data: {{line}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 }, label: 'Akademi' }, ], { ...

Retrieve a JSON object by making a request to a URL with specific parameters

Struggling with a common coder's mental block: The idea: Imagine entering a URL like www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345 Rather than receiving a webpage, the goal is to get back a json object for parsing on anoth ...

Barely populated React application following setup

I have been diving into React for quite some time now. However, today when I attempted to start a new project, it generated an almost empty project. My usual command create-react-app 'name-of-my-app' was used. It ran for a while and completed th ...

Encountering a problem with npm reading dependencies

I decided to kickstart a new Node application by following a tutorial and creating a package.json file. Below is the content of my json file: { "name": "Dashboard", "version": "0.0.0", "description": "Client-A Dashboard", "dependencies": { ...

Tips for turning off hash-based redirection in AngularJS

Here is a specific URL: http://www.something.com/sometest/test/#registration Some code has been written based on #registration for Internet Explorer. However, when using AngularJS, it redirects to the following URL, which disrupts the logic: http://www ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...

Leveraging npm packages in Meteor's Angular 1.3 framework

Although it may sound like a silly question, I am still confused. It has been said that Meteor has native support for npm modules in version 1.3. I am currently using Meteor with Angular integration. From the tutorial, it appears that using npm modules sh ...

Searching for partial nodes

I came across a helpful tutorial that explains how to perform a partial search. My goal is to have it so that when someone enters the text geor, it can locate a user named george. db.stores.find({storeName : {$regex : /Geor/}}).pretty() However, I am str ...

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

What is the best way to use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...

Is there a more efficient approach to extracting the border width using javascript?

I implemented the following code: const playGard = document.getElementsByClassName("playGard")[0]; const borderW = getComputedStyle(playGard,null).getPropertyValue('border-left-width').substr(0,2); The result I obtained was "10". Is there a m ...

Aurelia's navigation feature adds "?id=5" to the URL instead of "/5"

I have set up my Aurelia Router in app.ts using the configureRouter function like this: configureRouter(config, router: Router) { config.map([ { route: ['users', 'users/:userId?'], na ...

I am encountering an issue while trying to update SQL data from within a Node.js

Using a for-loop to update SQL command is common practice. Here's an example: for(var i=count1; i < count2;i++){ Book.TimeStart = Times[I] console.log(Book.TimeStart) sql = sql + `UPDATE projectroom.Details SET BookingId = `+Book.Bo ...

The logical OR operator in JavaScript (denoted as ||)

Can anyone explain the functionality of this operator in JavaScript? I have come across this operator in two different contexts: //context 1 function(e){ e = e || window.event; //context 2 if(a || b) In C or C++, I understand that the return value of th ...

How can I retrieve information on a logged in Auth0 user from an API?

I'm currently working on a React application that utilizes auth0 in conjunction with an express API server. One issue I'm facing is how to access user information within the API when a secure endpoint is called. While I can retrieve user data on ...

What is the best way to simulate an unexported function in Javascript jest environments?

Testing a module in my vuejs project is what I'm currently focusing on. import { getBaseUrl } from "@/application/api/baseUrl"; export default ( uri: string, requestBody: Record<string, string | number> ): void => { let form ...

Tips for utilizing JavaScript to upload a file in Webform and make it accessible in the global PHP variable $_FILES

I'm feeling a little overwhelmed and frustrated. I've come across a bunch of solutions, but none of them seem to work fully or correctly!? My task is to create an HTML form that allows users to upload one or more files to the web server using AJ ...

Firebase Auth in Vue.js is having trouble accurately verifying error messages when resetting passwords

As I work on sending a password reset email to a user, Firebase throws an error called RESET_PASSWORD_EXCEED_LIMIT when the number of requests goes beyond a certain limit. I am attempting to capture this error message in order to notify the user that thei ...

I'm curious about the outcomes of the JavaScript test. Could someone provide an explanation

Recently, I was in the process of writing a blog post discussing the importance of checking for the existence of jQuery elements before attaching event handlers. To illustrate this, I quickly created a jsfiddle example here. What puzzles me is that the re ...