首页 > 解决方案 > 如何从我的 firebase 用户列表中获取随机用户?

问题描述

我正在开发一个应用程序,需要从我的 firebase 用户列表中获取一个随机用户。每当用户注册时,系统都会更新特定节点上的用户计数。所以,我画了一个从 1 到总用户的数字。现在,如何根据该数字选择用户?

标签: javascriptfirebase

解决方案


假设您的所有用户都存储在 /users 节点中,其中包含他们的 uid 键并假设 uid 是有序的(它们总是如此),有几个选项。

1) 将 /users 节点中的所有用户加载到一个数组中,然后通过它的索引选择您想要的用户。假设我们想要第四个用户:

let usersRef = self.ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { snapshot in
    let allUsersArray = snapshot.children.allObjects
    let thisUserSnap = allUsersArray[3]
    print(thisUserSnap)
})

虽然这适用于少量用户,但如果您说 10,000 个用户和每个节点中存储的大量数据,它可能会使设备不堪重负。

2)创建一个单独的节点来存储uid。这是一个小得多的数据集,其工作方式与 1) 相同

uids
  uid_0: true
  uid_1: true
  uid_2: true
  uid_3: true
  uid_4: true
  uid_5: true
  uid_6: true
  uid_7: true

3) 进一步减小数据集的大小。既然您知道您有多少用户,请将数据集分成两个部分并使用它。

使用与2相同的结构)

let uidNode = self.ref.child("uids")

let index = 4 //the node we want
let totalNodeCount = 8 //the total amount of uid's
let mid = totalNodeCount / 2 //the middle node

if index <= mid { //if the node we want is in the first 1/2 of the list
    print("search first section")

    let q = uidNode.queryLimited(toFirst: UInt(index) )

    q.observeSingleEvent(of: .value, with: { snapshot in
        let array = snapshot.children.allObjects
        print(array.last) //the object we want will be the last one loaded
    })
} else {
    print("search second section")

    let q = uidNode.queryLimited(toLast: UInt(index) )

    q.observeSingleEvent(of: .value, with: { snapshot in
        let array = snapshot.children.allObjects
        print(array.first) //the object we want will be the first one loaded
    })
}

此方法仅返回列表的 1/2,因此它是更易于管理的数据量。


推荐阅读