gpt4 book ai didi

javascript - 使用 Node js 从 firebase auth 检索多个用户信息

转载 作者:行者123 更新时间:2023-12-02 21:02:46 25 4
gpt4 key购买 nike

我正在使用 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 函数检索用户信息。但它没有返回任何错误。

谢谢。

最佳答案

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

  • 您将 async/awaitthen() 一起使用,这是不推荐的。仅使用其中一种方法。
  • 如果我正确理解您的目标(“检索特定经理下的员工信息”),您不需要将 emp_uid 参数传递给您的函数,但对于每个 snap 您需要使用 snap.data().emp_uid
  • 读取 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) {
//...
}
},
};

关于javascript - 使用 Node js 从 firebase auth 检索多个用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com