在 Firebase 中按多个键查询 [英] Querying By Multiple Keys in Firebase

查看:33
本文介绍了在 Firebase 中按多个键查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Firebase 数据库中有一个已知键的列表

I have a list of known keys in my Firebase database

-Ke1uhoT3gpHR_VsehIv
-Ke8qAECkZC9ygGW3dEJ
-Ke8qMU7OEfUnuXSlhhl

我如何在一个统一的请求中查询这些键中的每一个,而不是遍历这些键中的每一个来获取其各自对象的快照?Firebase 是否提供此功能?

Rather than looping through each of these keys to fetch a snapshot of their respective object, how can I query for each of these keys in one single, unified request? Does Firebase provide this?

我发现了 Promise.all() 函数,它看起来很有前途(我发誓没有双关语),但我不确定如何使用获取 firebase 数据的标准方法来实现它,例如所以

I've discovered the Promise.all() function which looks promising (no pun intended I swear) but I'm not sure how to implement it using the standard way of fetching firebase data like so

var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
  var username = snapshot.val().username;
});

感谢您的帮助!

推荐答案

正如 David 的评论所建议的:如果这些项目以某种方式相关,您可以构建一个查询来获取它们.

As David's comment suggested: if the items are in some way related, you may be able to built a query to get them all.

否则就可以解决问题:

var keys = [ 
  "-Ke1uhoT3gpHR_VsehIv",
  "-Ke8qAECkZC9ygGW3dEJ",
  "-Ke8qMU7OEfUnuXSlhhl"
];
var promises = keys.map(function(key) {
  return firebase.database().ref("/items/").child(key).once("value");
});
Promise.all(promises).then(function(snapshots) {
  snapshots.forEach(function(snapshot) {
    console.log(snapshot.key+": "+snapshot.val());
  });
});

请注意,使用单独的请求检索每个项目并不像您想象的那么慢,因为所有请求都是通过单个连接发送的.有关详细说明,请参阅 通过使用查询而不是重复观察单个事件来加快为我的社交网络应用获取帖子.

Note that retrieving each item with a separate request is not as slow as you may think, since the requests are all sent over a single connection. For a longer explanation of that, see Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

这篇关于在 Firebase 中按多个键查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆