Using Firebase Query Functions in a CRUD Application
You will learn how to use Firebase events to make a query cross platform app development frameworks to the real-time database. You will learn how to sort and filter the data after that.
I will be showing you how to use a query function.
Making a query to the Firebase Real-time Database is completely different from traditional queries.
Trust me it’s not that hard! 🙂
Let’s split this article into FOUR parts.
I have already covered this in one of my other Firebase links.
There is a Firebase App on the Firebase console.
Permission can be granted to the Firebase database.
The sample file should be imported to the database.
“name”: “Alex Meraz1”
import the above code into your Firebase Database to create a janet file.
Go to develop a database and get started.
Click the ellipsis icon at the right to choose the import option.
The ellipsis icon is at the right. Choose the file that you created with the sample code
I have users at the top level in the structure of the database data, which is in the format of json.
I have a few user objects with a push key that is automatically generated when you insert a new object.
You can check it out if you want to use a different browser. The process is similar to what I will be doing.
I know that setting up the Node.js project will involve some Terminal / Command prompt code
I know some of you don’t like it, but this is not that bad and you’re good to go.
Go to the official site of Node.js to download and install it. If the version number is shown, open up Terminal and type in the name of the version you want. There is a folder on your computer. You can change the directory by issuing this command. If you want to install firebase, run npm init and issue this command. If you open the fire base-query folder in your text editor, you should see the module folder. Then, make an index.js file. The code is inside the file at the top.
var fire base is required, fire base.App is required, fire base.database is required, fire base.console is required.
In the first line, I import firebase.
I used the initializeApp method on the fire base after that.
The method takes an object as an argument that has only one property for now, called databaseURL, and replaces the URL with yours.
You can get your databaseURL by going to the Firebase console.
I use users as I am going to unitize the data only inside the users node and I use a reference to the database location path as the reference.
If everything goes according to plan, you will get the console.log(db Ref) message printed with the whole bunch of data.
Every time you make a change to an index.js file, you need to run the index.js to see the result in the terminal window.
Here are the FOUR important Firebase events:
- value()
- child_added()
- child_changed()
- child_removed()
You can use these events to query data from Firebase Database.
a) Value
When there is a change in the database reference, the value event will start.
This event will fire on page load for the first time
I get the newly updated snapshot when I make changes to the database.
All you have to do is to:
1. Create a database reference.
const dbRef = firebase.database().ref(“users”)
Attach the event with the method on.
This method will return full user, if this key is used.
The on method is used to observe the value event when there is a change in the database.
You can use both methods.
Once method will only fire once and will not listen for database changes.
The method will only fire once, unlike the method which will listen for database changes. The method detaches the event listener from the database reference.
This on method will take two arguments,
- Value – Event Name
The second argument is theCallback function which will give you all the information you need from the database.
Once you get the snapshot object, you can make changes to it inside the function.
Snapshot object has a lot of methods and properties. I will show you three things.
- The root key for the console would be output by this property.
This method will return the value of the three user objects.
In this case, the three user objects.
You can read more about the data snapshot here.
I have a way to use Promises.
3. Working with Promises
You can watch the video if you don’t know what a promise is.
Promises can be used for better multiple asynchronous operations.
Actually, console.log(dbRef.once(“value”)); returns promise.
“value” then “snap error console.log”
If you have a lot of user objects, the value event won’t scale well.
I would use Child_Added for a large dataset.
b) Child_Added
The child_added event will not loop through the user objects, unlike value event.
The child_added event only fires when a new object is added to the database
You can only get the newly added user object from the callback, not the whole object.
The child added event is more efficient than the value one.
The added event is very similar to the value event.
dbRef.on(“child_added”, snap => { console.log(snap); });
If you’ve already created a database reference, you can use the same variable over and over again.
Pretty straight forward…
c) Child_Changed
The child changed event will not fire like value and child added events.
The child_changed event will only start if there is a change in the value of any property or in the database.
You can update and render the view if the update object is available.
The creation of child_ changed is the same as the creation of child_added.
// will return an updated user object
d) Child_Removed
You have guessed it :),
When an object is removed completely, the child_removed event will start.
It is recommended to use child_added, child_changed and child_removed events instead of using value event.
You will have more control and it will be quicker.
The rest of them will happen if you create a local variable and sync with the database.
Order Functions are great for Sorting Data,
orderByChild() orderByKey() orderByValue()
a) orderByChild()
The order by clause is similar to the order by function and it is useful if you have a background in the database.
The child_added event example shows you how to get user data. If you want to sort the data by child, use order by child.
Attaching the database reference to the method and passing the child name is how you use the order by child function.
dbRef.orderByChild(“age”).on(“child_added”, snap => { console.log(snap.val()); });
The order by child will be sorted by order.
b) orderByKey()
I want to talk about the push key, which is a long string with a name that you can see in the sample data, as a key for each user object.
The push keys will be generated. Every time a new data is added, a push key is created for the user.
Push keys are created based on the time that the data is saved, so they will be similar to id in a database.
When you use the fire base events to query data, you will get data order byKey, oldest at the top and latest at the bottom.
dbRef.on(“child_added”, snap => { console.log(snap.val()); });
You can learn how push keys are used in my other app.
c) orderByValue()
This will only be used when you have data in a database like this.
{ “L6sDmT0yPtPFIMOj40s”: “Apple”, “L6dsDmTf0yPtPF7MOj4s”: “Orange”, }
You can use order by value to sort the data.
dbRef.orderByValue().on(“child_added”, (snap) => { console.log(snap.val()); });
If you find another way to use order by value, leave a comment.
Moving on to…
You can combine the order functions with the database queries.
The important query functions are listed here.
LimitToFirst(#) LimitToLast(#) StartAt() endAt(#) equalTo(“child_key”)
- LimitToFirst(#)
I use an argument 1 in the below example. The first object will be returned from the database reference. The value can be changed based on how many items are needed.
dbRef.limitToFirst(1).on(“child_added”, (snap) => { console.log(snap.val()); });
Let’s combine with the order function.
dbRef.orderByChild(“age”).limitToFirst(1).on(“child_added”, (snap) => { console.log(snap.val()); });
The above example first orders the data in ascending order by child age, then limits the first item based on the top from the order function result.
You will get a warning like this when you run the above example.
There is a fire base warning. Your data will be uploaded to the client. Adding email to your security rules for better performance would be a good idea.
The child key age can be index by adding a security rule to the database.
If you want to use the code below, you have to go to the Firebase console and replace it with the one below.
“rules”: “true”, “.write”, “$uid”
- LimitToLast(#)
The last object will be returned from the bottom of the list. The value can be changed based on how many items are needed.
dbRef.limitToLast(1).on(“child_added”, (snap) => { console.log(snap.val()); });
StartAt(“value”)
The startat function will only return the objects from the database after the value specified in an argument.
You will get all the user objects from the object with theRaja Tamil value.
dbRef.orderByChild(“name”).startAt(“Raja Tamil”).on(“child_added”, (snap) => { console.log(snap.val()); });
EndAt(“value”)
The endAt function only returns the user objects if the value specified in the argument matches the child name.
In the below example, you will get all the user objects starting from the top.
dbRef.orderByChild(“name”).endAt(“Raja Tamil”).on(“child_added”, (snap) => { console.log(snap.val()); });
EqualTo(“value”)
The function is straight forward. You can use this to get a specific user object by any of the child keys.
The child name is used in the order function to put the value that I want to equal to in the equalTo function as an argument.
dbRef.orderByChild(“name”).equalTo(“Raja Tamil”).on(“child_added”, (snap) => { console.log(snap.val()); });
EqualTo is very similar to the WHERE clause.
Conclusion
I mentioned at the beginning of the article that it’s very easy to query data in Firebase using value, child_added, child_changed and child_removed.
If you combine Firebase Events with order functions, you can sort data.
You can create powerful and complex queries by combining the order functions with the query functions.
What queries do you think you can do in a database?
0 Comments