【问题标题】:Retrieve multiple users info from firebase auth using Node js使用Node js从firebase auth中检索多个用户信息
【发布时间】:2020-08-01 18:25:32
【问题描述】:

我正在使用 Firebase 身份验证来存储用户。我有两种类型的用户:经理和员工。我将经理的 UID 与员工的 UID 一起存储在 Firestore 员工中。结构如下图。

Firestore 结构

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

现在我想执行一个查询,例如“检索特定经理下的员工信息”。为此,我尝试运行以下代码。

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.";
        });
    }
}

以上代码返回{}。我试图通过从特定行返回数据来进行调试。我知道问题在于使用我在forEach 循环中使用的firebase auth 函数检索用户信息。但它没有返回任何错误。

谢谢。

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore firebase-authentication


    【解决方案1】:

    您的代码中有几点需要更正:

    • 不建议将async/awaitthen() 一起使用。仅使用其中一种方法。
    • 如果我正确理解您的目标(“检索特定经理下的员工信息”),您不需要将emp_uid 参数传递给您的函数,但对于每个snap,您需要阅读emp_uid 字段的值与 snap.data().emp_uid
    • 最后,您需要使用Promise.all()并行执行所有异步getUser()方法调用。

    所以以下应该可以解决问题:

      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) {
            //...
          }
        },
      };
    

    【讨论】:

    • 有没有办法只获取displayName 字段而不是从firebase auth 获取整个用户对象?
    • 不,`getUser()ˋ 方法返回完整的 `UserRecord`。
    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 2018-12-06
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多