Bhuvan Gandhi
Bhuvan Gandhi

Reputation: 177

Retrieve multiple users info from firebase auth using Node js

I am using Firebase authentication to store users. I have two types of users: Manager and Employee. I am storing the manager's UID in Firestore employee along with the employee's UID. The structure is shown below.

Firestore structure

Company
|
> Document's ID
              |
              > mng_uid: Manager's UID
              > emp_uid: Employee's UID

Now I want to perform a query like "Retrieve employees' info which is under the specific manager." To do that I tried to run the below code.

module.exports = {
    get_users: async (mng_uid, emp_uid) => {
        return await db.collection("Company").where("manager_uid", "==", mng_uid).get().then(snaps => {
            if (!snaps.empty) {
                let resp = {};
                let i = 0;
                snaps.forEach(async (snap) => {
                    resp[i] = await admin.auth().getUser(emp_uid).then(userRecord => {
                        return userRecord;
                    }).catch(err => {
                        return err;
                    });
                    i++;
                });
                return resp;
            }
            else return "Oops! Not found.";
        }).catch(() => {
            return "Error in retrieving employees.";
        });
    }
}

Above code returns {}. I tried to debug by returning data from specific lines. I got to know that the issue is in retrieving the user's info using firebase auth function which I used in forEach loop. But it is not returning any error.

Thank you.

Upvotes: 0

Views: 297

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

There are several points to be corrected in your code:

  • You use async/await with then() which is not recommended. Only use one of these approaches.
  • If I understand correctly your goal ("Retrieve employees' info which is under the specific manager"), you do not need to pass a emp_uid parameter to your function, but for each snap you need to read the value of the emp_uid field with snap.data().emp_uid
  • Finally, you need to use Promise.all() to execute all the asynchronous getUser() method calls in parallel.

So the following should do the trick:

  module.exports = {
    get_users: async (mng_uid) => {
      try {
        const snaps = await db
          .collection('Company')
          .where('manager_uid', '==', mng_uid)
          .get();

        if (!snaps.empty) {
          const promises = [];
          snaps.forEach(snap => {
            promises.push(admin.auth().getUser(snap.data().emp_uid));
          });

          return Promise.all(promises);  //This will return an Array of UserRecords

        } else return 'Oops! Not found.';
      } catch (error) {
        //...
      }
    },
  };

Upvotes: 1

Related Questions