Firebase – Querying using Angularjs

What’s up guys, Eze is here. I already did couple of posts about Firebase and how to use the Real-Time database and the storage with AngularJs in case you missed it you can check here. Today I want to go further and give you some details on how to querying.

Understanding the reference object

As you already know we can define a reference object just by calling the following functions in the database object: firebase.database().ref(). This reference object offers you a bunch of functions to query our database paths in order to return just a subset of objects.

Using orderByChild(), orderByKey(), orderByPriority(), and orderByValue()

Using this set of functions allow us to create a new query reference that will be sorted by different properties for example by child will sort the subset by a specific property within the returned data,  or by key which of course if going to sort the subset by the object key.

Using startAt(), endAt(), and equalTo()

Using this set of functions allow us to generate a query with a subset of object that matches with the specified conditions. For example we can use equalTo chained with orderByChild in order to sort the subset by an specific property and then filter this subset to the results that match with an specific condition as I did in the example below.

 function getPlacesByUser(uid) {
if (!places) {
places = $firebaseArray(firebaseDataService.places.orderByChild('userId').equalTo(uid));
}
return places;
}

Applying those function as you can see it’s really easy to query our database in order to get the specific results we need. I have a working example in this link if you want to see the complete implementation. In this example I filter the result by user uid.

It’s important to highlight the reference object only accepts one orberByChild function in the chain, that means you can’t use it twice to filter the subset by two different properties. If you want to do that you need to add a property to the object which is a combination of the properties you want to filter.

For a complete reference of Angular Fire use this link.

For a complete reference of Firebase use this link

For a complete list of querying functions you ca use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s