javascript - 如何从我的 firebase 用户列表中获取随机用户?
问题描述
我正在开发一个应用程序,需要从我的 firebase 用户列表中获取一个随机用户。每当用户注册时,系统都会更新特定节点上的用户计数。所以,我画了一个从 1 到总用户的数字。现在,如何根据该数字选择用户?
解决方案
假设您的所有用户都存储在 /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,因此它是更易于管理的数据量。
推荐阅读
- java - 如何在第三级使用 Radio Groups 实现三级可扩展列表/回收站视图/树形视图
- javascript - 使用 ngFor 添加具有多个数组的项目
- node.js - 使用letsencrypt和nodejs设置SSL
- arrays - 是否有关于何时使用 JSON 对象而不是带有“名称”键的数组的经验法则?
- powershell - powershell - zabbix 采用 cpu 进程并发送 %
- python - 为什么 import subprocess.Popen 不起作用,而 from subprocess import Popen 起作用?我允许在 python 中导入什么“类型”的对象?
- wpf - 将多个 ItemsControl 绑定到一个 ObservableCollection
- swift - 按日期对 HealthKit 数据进行排序
- react-native - 在 RN 中使用多个视图时的边距
- math - 三次贝塞尔路径——在拉直弧长的同时保持弧长