【发布时间】:2018-07-21 21:15:27
【问题描述】:
我正在开发一个应用程序,需要从我的 firebase 用户列表中获取一个随机用户。每当用户注册时,系统都会更新特定节点上的用户计数。所以,我画了一个从 1 到总用户的数字。现在,如何根据该数字选择用户?
【问题讨论】:
标签: javascript firebase
我正在开发一个应用程序,需要从我的 firebase 用户列表中获取一个随机用户。每当用户注册时,系统都会更新特定节点上的用户计数。所以,我画了一个从 1 到总用户的数字。现在,如何根据该数字选择用户?
【问题讨论】:
标签: javascript firebase
假设您的所有用户都存储在 /users 节点中,其中包含他们的 uid 键,并假设 uid 是有序的(它们总是如此),有几个选项。
1) 将 /users 节点中的所有用户加载到一个数组中,然后通过它的索引选择您想要的用户。假设我们想要第 4 个用户:
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,因此它是更易于管理的数据量。
【讨论】:
如果您谈论的是经过身份验证的用户,检索他们列表的唯一方法是调用相应的 admin function 并在之后对其应用您的逻辑。
另一种方法是编写trigger for your authentication 并将用户ID 存储为递增数字(并且可能保存一个totalUser 字段),然后您只需要生成一个随机数并访问所述用户。
【讨论】: