Struggling to store a new user in Firebase Database

I have been researching extensively and am struggling to get any data to show up in the firebase database. I am aiming for this specific structure:

"my-app-name": {
    "users": {
        "uid-of-user": {
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="403428252d003428252d6e232f2d">[email protected]</a>",
            "todoitems": {
            }
        }
    }
}

Initially, I am unsure about how to implement this structure. In the visual editor, under "my-app-name", I have inputted "users" = "". I am uncertain if this is the correct way to start establishing users as an empty object. Perhaps I should not be using the visual editor at all? Below is my createNewUser controller responsible for storing new users in the database:

function LoginController($scope, Auth, $state, $location, $firebaseObject, $firebase) {
    $scope.createNewUser = createNewUser;
    $scope.signupComplete = "";

    function createNewUser() {
        var ref = new Firebase("https://sizzling-torch-655.firebaseio.com/");

        //CREATE USER
        Auth.$createUser({
            email: $scope.email,
            password: $scope.password
        }).then(function(userData) {

            //THIS SHOULD BE PERSISTING IT TO THE DATABASE
            var user = $firebaseObject(ref.child('users').child(userData.uid));
            user.$loaded().then(function() {
                var newUser = {
                    emailAddress: $scope.email,
                };
                user.$ref.$set(newUser);
            })
            // $location.path("/home");
        }).catch(function(error) {
            $scope.responseMessage = error;
        });
    };
};

I want to emphasize that the 'users' object has not been created in the firebase database yet. Any assistance would be greatly appreciated. Thank you.

Additional Information

Auth.$creatUser is defined as:

app.factory("Auth", ["$firebaseAuth", function($firebaseAuth) {
    return $firebaseAuth(ref);
}]);

Although I successfully created users and can see them in the Login/Users tab of the Firebase dashboard, I am unable to store them in the database.

The userData.uid refers to the unique identifier returned from the then block of the $createUser function.

UPDATE 2 Here are my security rules. Could these be preventing me from writing user data to the database? This app will be a todo list application, where users should only be able to access their own data.

{
  "rules": {
    // public read access
    ".read": true,

    "users": {
      "$uid": {
        ".write": "$uid === auth.uid"
      }
    }
  }
}

Answer №1

If you are using Firebase Authentication, it does not automatically store user information in the database. To store such information, you will need to write the code yourself.

Looking at your snippet:

//THIS SHOULD BE PERSISTING IT TO THE DATABASE
var user = $firebaseObject(ref.child('users').child(userData.uid));

This code actually does not save any information in the database. Instead, it attempts to retrieve the user's data from the database. Since the data was not initially written there, the retrieval will be unsuccessful and the then() function will not execute.

The solution is to write the necessary user data into the database when the user authenticates.

var user = $firebaseObject(ref.child('users').child(userData.uid));
var newUser = {
    emailAddress: $scope.email,
};
user.$ref.$set(newUser);

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

How to implement mouse hover functionality in C# using Selenium?

When attempting to mouse hover on a menu with multiple sub-menus, I encountered an issue where the suggested actions caused other menus to overlap and hide the intended element. Below is the recommended code snippet for hovering over the desired element: ...

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...

Exploring the syntax of Vue's data function

I encountered a syntax error while compiling my assets: Syntax Error: SyntaxError: C:\xampp\htdocs\dtcburger.com\resources\js\components\stripe\STRIPEform3.vue: Unexpected token, expected ";" (51:12) 49 | { ...

What could be causing issues with my JavaScript AJAX?

I'm in the process of developing a basic chat system that automatically loads new messages as they come in. Initially, I used to fetch all messages from the database. However, I encountered an issue where the scroll bar would constantly jump to the bo ...

I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html> <html> <head> <title>Canvas Compositing Tutorial</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br> <butt ...

Click the Button to Trigger Database Update

I have been struggling with updating a dynamic table that allows inline editing and dynamically adding rows. My goal is to click a save button that triggers an UPDATE query to modify the database. Unfortunately, I can't seem to figure it out on my own ...

How can I find the length of an array in Mongoose without using

This is the model I am currently working with: const postSchema = Schema( { author: { type: Schema.Types.ObjectId, ref: "User", }, likes: [{ type: Schema.Types.ObjectId, ref: "Like", },], ...

Adobe Acrobat does not run JavaScript code in documents that are submitted for electronic signatures

Lately, I have been experiencing issues with pdfs that contain embedded javascript. The strange thing is that the javascript functions perfectly in the Acrobat Pro DC app but fails to execute when the document is sent for signature. To troubleshoot, I cre ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Creating an automatic image carousel using a combination of Jquery, Javascript, and CSS

I have been working on creating a slider using jQuery and javascript, but I am facing some issues with the autoplay functionality and the next-previous buttons. This slider is intended for displaying images as a title indicates. Can anyone assist me with i ...

fade out row upon successful deletion using ajax

My code includes an AJAX function to delete items by row. In my table, there is a column with the action to perform the deletion. Here is the AJAX function: //delete detail function deleteDetail(id_po_req_detail) { var tr = ...

I need assistance in locating an error; the error message states that $ is not defined and an object is expected

Issue with $ not being defined, object expected.. I am trying to verify if all sets of radio buttons are checked when a button is clicked! Please help. <script type="text/javascript> $(document).on('click', 'form', function () { ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

The phonegap page redirection is failing, as the 'location' property of the object does not function correctly

I'm attempting to implement a straightforward page redirection in PhoneGap using JavaScript. Within an iframe, I have the following code: window.parent.location("event_select.html"); Unfortunately, this approach is unsuccessful and results in the fo ...

.toggle function malfunctioning

Upon page load, I have a script that toggles the County menu. The goal is to hide the county menu if any country other than "United Kingdom" is selected on page load. If the user selects another country after the page has loaded, there is an issue where ...

The curious conduct of wild safari creatures

I have been using JavaScript to split my ePub chapter into pages by wrapping the code with new divs that represent separate pages. I have also created CSS styles for these new divs. Everything works perfectly when the file has a filename extension of &apos ...

Centralized Vendor Repository for Managing Multiple Angular2 Applications

Looking to host different Angular2 apps that share the same framework packages and node_modules across a main domain and subdomains: domain.com subdomain.domain.com sub2.domain.com Directory Layout public_html ├── SUBDOMAINS │ ├── sub2 ...

Ways to determine if the keys of an object are present in an array, filtered by the array key

Working on an Angular 2 Ionic application and I'm wondering if there's a straightforward way to filter individuals by age in a specific array and then verify if any key in another object matches the name of a person in the array, returning a bool ...

Essential Understanding of HTML Query Strings Required

As a newcomer to the world of web design, I have taken on what seems like a challenging task for me: creating a webpage that can send a query string to the German Railway website (bahn.de) with the parameters I input. My question now is whether there is a ...