When accessing Firestore data using .data(), it may sometimes return as

I am currently developing an application using React and Node.js for the server, with Firebase Auth and Firestore integration.

However, I have encountered a problem. When I create a user, everything seems to work fine. The user is created successfully, their UID and data are stored in the database. But when I try to retrieve the user data, it returns as undefined:

async function getUserData(uid) {
    const docRef = doc(db, `users/${uid}`);
    const docSnapshot = await getDoc(docRef);
    console.log(docSnapshot);
    const data = docSnapshot.data();
    console.log(` data: ${data}`);
    return data;
  }

The console output shows that the docSnapshot is correct, but the .data() call afterwards results in undefined:

User data is not being displayed.

Here is how I create users using the Firebase-admin SDK to ensure only admins can create new users:

async function createUser(email, password, name, role) {
    axios
      .post('http://localhost:5000/api/user', {
        email: email,
        password: password,
        name: name,
        role: role,
      })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });

    axios.get('http://localhost:5000/api/user/info').then((info) => {
      const docRef = doc(db, `users/${info.data.uid}`);
      setDoc(docRef, { email: email, name: name, role: role });
    });
  }

Server-side code:

app.post('/api/user', jsonParser, (req, res) => {
  const user = req.body;
  getAuth()
    .createUser({
      email: user.email,
      password: user.password,
      displayName: user.name,
    })
    .then((userRecord) => {
      console.log(userRecord);
      app.get('/api/user/info', (req, res) => {
        res.send(userRecord);
      });
    })
    .catch((err) => {
      console.log(err);
    });
});

Answer №1

I recently made an update to how I store user information in the database. Previously, I stored user data on the front end, but now I've migrated everything over to the server for better security.


    app.post('/api/user', jsonParser, async (req, res) => {
      const user = req.body;
      console.log(user);
      await getAuth()
        .createUser({
          email: user.email,
          password: user.password,
          displayName: user.name,
        })
        .then((UserRecord) => {
          db.collection('users').doc(UserRecord.uid).set({
            email: user.email,
            name: user.name,
            rol: user.rol,
          });
        })
        .catch((err) => {
          console.log(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

Transform yaml strings into JSON entities

We are facing a challenge with two separate codebases that have different localization styles. One codebase uses yaml, while the other uses JSON. Currently, we are working on transitioning to the JSON-based codebase. However, with 20k yaml strings and sup ...

Display the output of JSON.stringify in a neatly formatted table

After sending my table data to the database using ajax, I am now trying to retrieve it by clicking on the open button. $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", ...

Exploring nested JSON data in Vue.js

In my attempt to access nested JSON within an array using Vue for a simple search functionality, I encountered a problem. Each school is encapsulated in a "hit" array, causing the system to perceive only one result of "hit" instead of returning data for ea ...

Array in JavaScript containing a replica set of Node.js and MongoDB

As a novice programmer with more experience in sysadmin work, I've been tasked with setting up a new HA environment for a node js application using MongoDB. The current setup utilizes mongojs and monq java classes with only one MongoDB instance. In or ...

Using React Native to implement a slide bar that displays an image

Currently working on an app and aiming to implement a slider feature for emoji selection. Despite searching for suitable packages, I have not been able to find one that fits my requirements. As a result, I decided to use the react native slider instead. Ho ...

Using v-for with TailwindCSS animations seems to cause issues

I'm currently working on implementing a list of pop-up messages in the upper right corner of the screen. These messages should disappear when clicked and include a slide-fade transition effect. The transition animation works fine when there is only o ...

What is the recommended way to initiate the first server-side external API query in Nuxt 3 and where should it be done?

I have a question regarding the process of developing web applications in Nuxt 3 using the composition API. I am working on an application that requires user location-dependent content. To achieve this, I need to determine the user's IP address using ...

Is it possible to establish a limit on a field's value in MongoDB?

Just a quick query - I'm curious if there's a feature in mongodb that allows for fields to have a set maximum value. For instance, let's say the field "cards" is restricted to a maximum value of 100. If an increment would exceed this limit, ...

Exploring locations using the Google Geolocation API

I have a website and am trying to determine the location of my visitors. I came across this code on Google Code: <script type="text/javascript" src="gears_init.js"></script> <script type="text/javascript"> var geo = google.gears.factory ...

Using jQuery, for every button click within a specific class, the content of a div stored in variables should be replaced based on the attribute value

I have a few buttons inside a div. The challenge is to display different content depending on the value attached to the "link" attribute after clicking. When a button is clicked, a function retrieves the value inside the "link" attribute and if it matches ...

ReactJS Error: Attempting to access undefined property "updateNumber"

Just getting my feet wet with js and React, attempting to create a simple Sudoku program. Encountering an issue when adding UpdateNumberInCell={this.updateNumber} as a property in the Cell component - receiving the error: "Uncaught TypeError: Cannot read ...

Run a Firebase backend and React frontend locally to troubleshoot and test together

I am currently in the process of constructing a website using React with a backend powered by Firebase functions. My approach involves utilizing firebase serve to locally host the node.js backend, which I connect to my React code through express API endpo ...

ExpressJS authentication -> PassportJS: Issue with setting headers after they have been sent

Currently, I am implementing authentication in Express.js using Passport.js. Below is the code snippet from my login.js file: passport.use(new LocalStrategy( function(username, password, done) { //console.log(username); Usercollectio ...

Error message: "An undefined index error occurred during an Ajax call to a

Path: homepage -> initiate ajax request to tester.php on PHP -> receive JSON data back to homepage. I am struggling to resolve this issue. Any help would be appreciated. AJAX Request: $.ajax({ url : "tester.php", ty ...

Troubleshooting why the Typescript Omit property is not functioning correctly when used with the 'as' keyword

When both properties are needed during registration, but only one is necessary after, the system utilizes Firebase built-in functions for authentication and registration purposes. All other information will be stored in the Firebase user collection. The i ...

What are the steps to create a responsive Coin Slider?

Once the slider is generated, it appears that there is no built-in method to resize it, causing issues with responsive design. Is there a way to adjust the size of the Coin Slider plugin based on the media queries in Twitter Bootstrap 3? Take a look at C ...

Is there a way to transfer the content of a div into a fresh window while retaining its original formatting

Here is a way to copy a new page: var yourDOCTYPE = "<!DOCTYPE html..."; // the doctype declaration var printPreview = window.open('about:blank', 'print_preview'); var printDocument = printPreview.document; printDocument.open(); pri ...

Automate the detection of a connected device via USB on a NodeJS server

I created a web interface for a colorimeter by using a NodeJS server that can read USB serial inputs through the serialport npm library. This information is then sent to a local web page. The colorimeter consists of a circuit with a microcontroller that is ...

Encountering an issue with setting up Pinia in Vue3, as it is showing an error message stating "

I am facing a challenge with my Vue app where the normal reactive store is not working correctly and does not retain the values I have set. Hence, I would like to switch to a Pinia store. After installing Pinia, my main.js file looks like this: import { cr ...

Transferring a JSON value to PHP and saving it in a MySQL database

I currently have JSON values stored in a variable called json_obj in JavaScript. My goal is to pass this data on submission and store it in a MySQL database using PHP. However, I am unsure of how to achieve this. var json_obj = [ {"id":"1","name":"mun ...