如何从Firebase用户列表中获得随机用户?

时间:2018-07-21 21:15:27

标签: javascript firebase

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

2 个答案:

答案 0 :(得分:0)

如果您谈论的是经过身份验证的用户,那么获取用户列表的唯一方法是调用相应的admin function并随后对其应用逻辑。

另一种方式可能是编写一个trigger for your authentication并使用递增的数字存储userId(并可能保存totalUser字段),那么您只需要生成一个随机数并访问该用户即可。

答案 1 :(得分:0)

假设所有用户都使用其uid的键存储在/ users节点中,并假定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,因此它的数据量更易于管理。