我正在编写一个从 Android
应用调用的 Firebase Cloud Function
。该函数应该从 Database
中的用户 Node 获取一个随机用户(任何随机用户,但不是发送请求的用户)并将其返回给客户端。问题是数据的结构不是数组(不应该也不能是)。
所以我不能选择一个随机数并读取该 Node ,我也不想读取所有用户 Node 并对其进行迭代,因为它包含很多用户,这会耗费时间和资源。 问题:
How can I get a random user different from the one who sent the request, and changes with every time the function is called (completely random), while not querying a lot of data from the database?
最佳答案
主要问题:
Firebase 不会跟踪我们进行随机化所需的子项计数。然而,我们可以使用 DataSnapshot.numChildren()
。
为避免这种情况,您可以将 count
元素添加到 /users
Node ,您必须使用云功能手动维护该 Node (例如,添加用户时,递增 count
,并在删除时递减)。
另一方面,由于云函数在服务器上,而 firebase 会为您管理缓存,因此实际使用 DataSnapshot.numChildren()
没什么大不了的,因为函数第一次执行时会缓存数据,只有在有变化时才会更新。
因此我建议使用 numChildren()
函数:
db.ref('/users').once('value').then(snapshot =>
Math.floor((Math.random() * snapshot.numChildren()))
);
或者使用 count
方法:
db.ref('/users/count').once('value').then(snapshot =>
Math.floor((Math.random() * snapshot.val()))
);
获取随机 Node :
db.ref('/users').orderByKey().startAt(random).limitToFirst(1);
方法一:
// https://stackoverflow.com/a/38423694/4161937
// attach permanent listener to force firebase caching (not sure if it works for this case)
db.ref('/users').on('value', () => {});
// will read #random amount of items
db.ref('/users').orderByKey().limitToFirst(random).once('value').then(users => Object.keys(users)[random]);
方法二:
// https://stackoverflow.com/a/38423694/4161937
// attach permanent listener to force firebase caching
db.ref('/users').on('value', () => {});
db.ref('/users').once('value').then(users => Object.keys()[random])
您可以在官方文档中阅读有关查询顺序和过滤的更多信息:
关于javascript - Firebase - 从数据库 Node 获取随机子 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539177/