Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying By Multiple Keys in Firebase

I have a list of known keys in my Firebase database

-Ke1uhoT3gpHR_VsehIv
-Ke8qAECkZC9ygGW3dEJ
-Ke8qMU7OEfUnuXSlhhl

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?

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;
});

Thanks for any help!

like image 230
Clay Banks Avatar asked Mar 05 '17 15:03

Clay Banks


People also ask

What is getKey () in firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.

Can we use SQL queries in firebase?

FireSQL is a library built on top of the official Firebase SDK that allows you to query Cloud Firestore using SQL syntax. It's smart enough to issue the minimum amount of queries necessary to the Firestore servers in order to get the data that you request.

What is DataSnapshot in firebase?

A DataSnapshot is an efficiently-generated immutable copy of the data at a Firebase Location.

Does firebase have primary key?

This chat application allows users to store the basic profile and contact list. The user profile would be located on a path such as Users/$uid. User is a node in it and will have a sort of primary key associated with an ID. So, we can access each one uniquely.


1 Answers

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.

Otherwise this would do the trick:

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.

like image 103
Frank van Puffelen Avatar answered Oct 20 '22 16:10

Frank van Puffelen