Error encountered while trying to access the user information from Firestore/Firebase

When I attempt to display the current user that is logged in

 console.log(firebase.auth().currentUser.uid)

The user's UID is outputted.
I then decided to retrieve the current user's information from Firestore using the following code:

  import firebase from 'firebase/app'
  import "firebase/auth"
  import db from '../firebase/firebaseInit'

  async getCurrentUser(){
    const database = 
    db.collection('users').doc(firebase.auth().currentUser.uid)
    const dbResults = await database.get()
    console.log(dbResults.data())
}

However, the result was undefined

Answer №1

db.collection("users").where("userId", "==","enter the ID here")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
           
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch((error) => {
        console.log("Error fetching documents: ", error);
    });

Answer №2

  1. Have you created a user collection in your Firestore database to store user information? Make sure to store the user's uid within it as Firestore does not do this automatically.

  2. Is your database properly configured? Have you been able to establish connections using other methods with the current db function?

Furthermore, it is recommended to rename your database variable to docRef and your result variable to docSnap for clarity and best practices as they refer to specific documents!

Answer №3

To retrieve the user id from the stored collection labeled as userId, you may attempt the following query:

db.collection('users').where('userId', '==', firebase.auth().currentUser.uid)

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

Exporting from Blender to three.js can sometimes result in misaligned object positions

Currently, I am encountering a challenge while exporting a basic scene from Blender to Three.js. Apart from the ongoing struggle with the texture not displaying properly, I have discovered an odd issue with the positioning of objects. The image below showc ...

Guide on redirecting the user to the "notFound" page within the getServerSideProps function in Next.JS whenever an incorrect params.id is provided

export const getServerSideProps = async ({ params }) => { const res = await fetch( `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}` ); const { hits } = await res.json(); if (!hits) { return { notFound: tr ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Select2 in Bootstrap does not trigger the select event when pasting until a word has been typed

One issue I encountered while using bootstrap select2 v4.* on my site (Yii 2.x) is that the event select2:select does not fire when text is pasted with ctrl+v until some text is manually typed. Once some text is entered, the event works as expected. What ...

Incorporate controllers dynamically into your Angular application

Currently, I am incorporating AngularJS into a Backbone.js application. The scenario is as follows: I have one controller (let's call it controller1) which is added to the Angular app from a Backbone view (referred to as view1). Subsequently, I introd ...

How can JavaScript allow access to files outside of a web server environment? Could .htaccess provide a

Currently, I'm facing a challenge with my local server on Mac 10.8. I am trying to serve files such as videos and images from an external hard drive. The path for the external hard drive is HD: /Volumes/ while the web server's path is /Library/Se ...

Omitting fields in the select statement when utilizing group by clauses

Scenario: In a database using HR schema, there are Employees and Departments tables. During an interview, I was given the task of writing a query with certain conditions. The task: Write a query to display department_name, department_no, and count of all ...

Display a loading spinner dialog using Jquerymobile until the page finishes loading

I am facing an issue with my app where I need to show a Loading dialog while sending data from the first page to the server. The goal is to display the Loading dialog until the send operation (posting to server) is complete and then proceed to page two. I ...

break LineSegment at specified location

Using the vertex positions provided below, I am creating a square using THREE.LineSegments (or even by a simple THREE.Line.) vertices: path.vertices = [ new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ), new THREE.Vector3( 10.6000061 ...

When working with a JavaScript array of class objects, it may appear as though the array is empty when it

Currently puzzled by the behavior of this array. Despite my efforts to find an answer, I haven't had any luck so far. I initialize var allMenuItems = []; at the top and then in getMenuItems(), I push multiple new class objects. However, when I call co ...

"Encountered an error when using the pop method on a split function: 'undefined is not

I am working with an array of filenames called ret, and I need to extract the extension of each file name. var cList=""; var fName=""; var ext=""; for(var i=0;i<=ret.length-1;i++){ fName=ret[i]; ext=fName.s ...

Saving information retrieved from queries using Mongoose and Node.js into variables for later use

I have some code located in app.js. var Song = db.model('Song'); var Album = db.model('Album'); My goal is to render the data to index.jade using two variables: a list of songs and a list of albums. I am querying the data l ...

How do I modify the height of a q-select component in Quasar?

I have been struggling to change the q-select in the quasar framework, despite numerous attempts. <q-select v-model="site1" outline dense class="selection" /> :deep(.selection .q-field__control) {font-size: 13px; width: 250px;} ...

Using Javascript, the sum of inputs is calculated based on the keyup event

I am a beginner in javascript and I'm learning about events. Below is the HTML code for a table that displays income titles and their respective prices. <table class="table table-hover table-bordered" id="incomeId"> <thead> <tr&g ...

Retrieving information from an Object within a JSON response

After calling my JSON, I receive a specific set of arrays of objects that contain valuable data. I am currently struggling to access this data and display it in a dropdown menu. When I log the response in the console, it appears as shown in this image: htt ...

Selenium throws an error message stating 'NoSuchAlertError: no alert is currently opened'

When using Selenium, I encounter an issue where clicking a button triggers an alert box, but accepting the alert box results in an error message. element.click(); driver.switchTo().alert().accept(); The problem is quite unpredictable. ...

React event handling

Currently, I am in the process of developing an accordion app using React. The data for this app is fetched from an API, and while I have the basic structure of the app ready, I am facing some difficulties with handling the click event on the accordion. H ...

Efficiently Fill JQUERY Mobile Multi-Pages with Dynamic Content

A Question for JQUERY Mobile Beginners: In my basic JQUERY Mobile application, I have a simple setup with two pages. When the user navigates to PAGE2, I need to make an AJAX call to retrieve a JSON object that contains a list of people along with their DB ...

Blocking certain charter inputs in ASP.NET can be achieved by implementing custom validation logic or

Here is an ASP.NET code snippet that prompts the user for input. The accompanying JavaScript ensures that the user does not leave the input field empty. Now, the goal is to prevent users from entering certain characters like (|,@,#,$) using the same JavaSc ...

Ways to update a component when the state changes

When attempting to access components that require authentication, I want to redirect to the login page if the user is not logged in. However, I am facing an issue with initializing the firebase auth object, as there is a small delay. The documentation sugg ...