Difficulty encountered when attempting to generate a Firestore document with the Firebase ID of a user

I am in the process of building a web application using Vue.js + Firebase. Currently, I am working on implementing a sign-up feature for the project.

The sign-up feature utilizes a Firebase auth function and it is functioning correctly. However, I also need to create a document in the Firestore 'users' collection where the document ID should be the same as the auth UID. Unfortunately, this part is not working as expected and I require some assistance.

const firebaseApp = firebase.initializeApp(firebase_config)
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export {db, auth};
import {db,auth} from '../plugins/firebase'

// ( omit ) //

methods: {
  // this works
  test: function(){
    db.collection("users").doc("new_user").set({
      displayName: "Bob",
    }).catch(error=>{
      console.log('error on debugging: ',error)
    })
  },
    
  register: function(){
    auth.createUserWithEmailAndPassword(this.user_mail, this.user_password)
    .then(result=>{
      // this works
      console.log(result.user.uid)

      // this does not work
      db.collection('users').doc(result.user.uid).set({
        displayName: 'John',
      }).catch(error=>{
        console.log('fail to add data: ',error)
      })
    })
    .catch(error=>{
      console.log('something goes wrong on auth: ',error)
    })
  }
}

Temporary Firestore security rules are set as follows:

match /{document=**} {
  allow read, write, create: if request.auth.uid != null;
}

Answer №1

When utilizing the AngularFire library, this is the recommended approach for writing to the database:


import { AngularFirestore } from '@angular/fire/firestore';

constructor(
        private angularFireStore: AngularFirestore,
        
    ) {}


methods: {
  register: function(){
    firebase.auth().createUserWithEmailAndPassword(this.user_mail, this.user_password)
    .then(result=>{
      // This section is functional
      console.log(result.user.uid);
      const userUid = result.user.uid;
      const data = {
          displayName: 'John',
       }

      createUserDoc(userUid, data);
    })
    .catch(error=>{
      console.log('An error occurred during authentication: ',error);
    })
  }
}

createUserDoc(userUid,userData){
   return this.angularFireStore.collection('users').doc(userUid).set(userData);

}

Answer №2

Below is the solution to resolve the issue. In case there are any complications while creating the user document, such as a security measure that blocks it, the catch block will alert you.

functions: {
  // ...
 
  registerUser: function(){
    auth.createUserWithEmailAndPassword(this.email, this.password)
    .then(response=>{
      // successful execution
      console.log(response.user.uid)

      // encountering an error here
      return db.collection('users').doc(response.user.uid).set({
        displayName: 'John',
      })
    })
    .catch(err=>{
      console.error('An error occurred during authentication: ', err)
    })
  }
}

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 can I prevent links from being deleted in a UML state diagram using Jointjs?

My UML state diagram created with jointjs features interconnected states linked through lines. When the links are hovered over, a cross symbol appears, allowing users to delete the link by clicking on it. I am looking to prevent the cross symbol from sho ...

excessive memory usage in a simple react-native application

My experience with creating my first react native app has been more challenging than I initially expected. I'm having trouble understanding what I might be doing wrong. Initially, the app is simple, fetching data through Redux. componentWillMount() ...

Struggling to locate the module 'firebase-admin/app' - Tips for resolving this issue?

While working with Typescript and firebase-admin for firebase cloud functions, I encountered the error message "Cannot find module 'firebase-admin/app'" when compiling the code with TS. Tried solutions: Reinstalling Dependency Deleting node_modu ...

The function sendKeys with protractor's Key.Tab input is failing to function

Currently, I am using Protractor along with JavaScript. The issue I'm facing is that the SendKeys(protractor.Key.TAB) function does not seem to be tabbing out from the input field. Please find below the HTML tag for the input field: <td> < ...

Search for data within a nested array using MongoDB aggregation techniques

In my data structure, I have nested array documents that are outlined below: countries: [ { "id": "id of country", "cities": [ { "id": "id of city 1", "areas": [ ...

Converting Roman Numerals into Decimal Numbers using JavaScript Algorithm

I am eager to develop a Javascript Algorithm that can convert Roman numerals to Arabic using the provided methods below. Array.prototype.splice() Array.prototype.indexOf() Array.prototype.join() I have managed to find an algorithm that accomplishes this ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...

How to apply a CSS style to a specific class based on conditions in Vue.js

Many questions have been asked about conditionally adding classes or styles to elements, but I want to take it a step further and conditionally style a class. In my application, users can customize foreground and background colors using a theming system. ...

The functionality of the jQuery validation plugin is failing to operate as intended

I attempted to implement a basic validation using the jQuery Validation Plugin, but I was unsuccessful. When I click the submit button, nothing happens. Can someone provide assistance with this issue? I have included the code below: Thank you in advance. ...

Best Practices for Naming Logout Endpoints in REST APIs

As someone who is just starting out with coding, I have a question about naming conventions for routes. When creating a route for adding a new user, I typically use something like this: router.post("/users", async (req, res) => {} And for l ...

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

What could possibly be causing SweetAlert to be overridden following every loop iteration?

I am facing a challenge with creating unique delete buttons for each of my activities. Whenever I try to implement sweetalert for the delete button, it seems to override itself after each iteration. This results in all buttons deleting the last item in the ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

What is the best way to ensure that JavaScript only impacts a specific element?

Looking for a simple JavaScript solution that toggles the "open" class on a specific element? I'm currently facing an issue where all elements with the classes .clickSlide and .sub_menu get the "open" class when any one of them is clicked. What I real ...

Managing npm overhead - strategies for handling it

When downloading packages through npm, I notice that it often includes unnecessary files along with the desired library. I usually just need the final build of the library or a *.min.js file, but end up with a lot more than that. How do you manage these e ...

``Can the content visible to an iframe be controlled by manipulating window.top?

There's a unique web application that functions by loading various iframes into itself. It offers some code that the child iframes can connect with. The child iframes use window.top, which is beyond my control but everything runs smoothly. Now, I ai ...

Implementing Click Event to Dynamically Created div using jQuery

I have recently started using JQuery and I am encountering difficulties in binding functions to a dynamically created div. When the user clicks on a button, new divs are added to a container along with a change in the background color of that container. U ...

Ways to implement two functions within a single onclick event

Is it possible to call two functions with onclick event? <input id = "test" onclick="func1()"> Can I add another function as well? How would I go about doing that? ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

PHP not able to retrieve JavaScript variable using Ajax

Resolved: I recently discovered that ajax only sends data in that particular moment, and redirecting creates a new instance. I spent hours searching through various Stack Overflow results for solutions, but none of them seem to work. My current challenge ...