【问题标题】:Read random user firestore读取随机用户firestore
【发布时间】:2020-11-29 23:05:56
【问题描述】:

每当用户使用 Firebase 身份验证在我的应用上注册时,我都会在 Firestore 的 users 集合中创建一个文档,其中存储伪、用户类型、性别等元数据...

为此,文档 ID 与 Firebase Auth 自动提供的 uid 完全相同(来自用户 UserRecord 对象)

现在,我的应用需要从 Firestore 中的 users 集合中随机获取一个用户。

我阅读了Firestore: How to get random documents in a collection,但这篇文章建议我自己创建 ID。该应用程序已使用 FirebaseAuth 生成的 ID 构建,那么解决方案是什么?

【问题讨论】:

  • 该方法将与您链接的答案相同:在客户端生成一个随机 UID 值,然后通过按 UID 排序在数据库中找到最接近的 UID,并从您生成的随机值。
  • @tsr 如果答案有效,您会标记为最佳答案吗?

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


【解决方案1】:

firestore 中的一个常见做法是在集合中创建一个“--Stats--”文档(--Stats-- 是文档 ID)。该文档可以包含有关集合的信息(文档数量、上次更新、集合权限等)。

在您的情况下,您可以使用云函数/触发器来跟踪用户集合中的用户总数,并将新用户的 id 添加到“userIds”数组中。您可以将这两个字段都保留在 users 集合的 --Stats-- 文档中。这样,当你想获取一个随机用户时,你可以随机生成一个介于 0 和文档计数之间的数字,然后将其用作 userIds 数组的索引。我可能看起来像这样:

var usersCollectionRef= db.collection("users");

usersCollectionRef.doc("--Stats--").get().then((doc) => {

    let numberOfUsers = doc.data().numberOfUsers; 
    let userIdArray = doc.data().userIds; 
    let randomNumber = Math.floor(Math.random() * (numberOfUsers + 1));

    return usersCollectionRef.doc(userIdArray[randomNumber]).get();

}).then((doc) => {
   ...do something with the user's document
})

【讨论】:

  • 我猜你不需要numberOfUsers,只需计算userIds
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
相关资源
最近更新 更多