Firebase Querying

Sean Dees
Sean Dees
Aug 22, 2017 · 2 min read

Recently I was tasked with creating a simple in-house wiki for my company and I thought this would be a good time to use Google’s Firebase for my back-end. I previously used Firebase to host a few web apps and was happy with the results.

If you’re not familiar with firebase, it’s a mobile and web application development platform from google. It offers a host of features and — best of all- it’s free (although there are fees for advanced features). The database portion of the platform is a NoSql database where data is stored in JSON format.

Querying Data

After the initial setup and once you’ve structured your data, we can begin querying for data. The first thing we’ll do is create a reference to the database

var db = firebase.database();

Next, we will reference our parent key by entering the path

var ref = db.ref('playerData/playerName/lebron');

Next we will attach an ordering function. Firebase currently has four ordering functions that we can use:

  1. orderByKey()
  2. orderByChild()
  3. orderByValue()
  4. orderByPriority()

In this example we will be using orderByKey, but the other ordering functions work similarly. Now we will attach the ordering function

ref.orderByKey().on('value',function(snapshot){
var data = snapshot.val();
for(key in data){
console.log(data[key));
}});

The code above will cycle through all keys on the lebron object and print them out to the console.

by adding a query function, we can be even more specific. Firebase has four query functions that we can use:

  1. equalTo
  2. limitToFirst
  3. limitToLast
  4. isEqual
  5. endAt

we will be using the equalTo query function to target apg (assist per game).

ref.orderByKey().equalTo('apg').on('value',function(snapshot){
var data = snapshot.val();
for(key in data){
console.log(data[key));
}});

that will print out 8.8 to the console.

conclusion

As you can see, querying in Firebase can be extremely easy. Just make sure that your data is structured properly. If not, you can run into time consuming problems.

)

Sean Dees

Written by

Sean Dees

I’m a husband, father and Web Developer from Detroit, MI currently residing in Windsor, ON, Canada

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade