Realtime Database in Firebase v9

How is a realtime database different from a static database?

Realtime Database as the name suggests allows the user to read and write to the database in realtime. The data stored in the database is in key-value format.  It’s an efficient, low-latency solution for mobile apps that require synced states across clients in realtime.

How the data is structured in the realtime database?

All Firebase Realtime Database data is stored as JSON objects. You can either provide your key or can generate unique keys using firebase also. Code to generate a unique key from firebase itself is as follows:-

Code to generate key

Read and Write in the Database

Write in the database.

 Initial Database

You can write data into the database by either the set() method or update() method.

  • set(): Saves data to a specified reference, replacing any existing data at that path. It can overwrite the entire object if all fields are not specified. Any manual error in referencing an object or its contents can lead to loss of data.

Code for set() 
After set()
  • update(): Saves data to a specified reference, replacing any existing data at that path. It doesn’t overwrite instead only deals with the specified fields.

Code for update()
After update()


Both set() and update() can return a Promise you can use to know when “write” is committed to the database.

Read the database

  • onValue(): You can use this event to read static snapshots of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot will return false when you call exists() and null when you call val() on it.

To limit the size of your snapshots, attach only at the lowest level needed for watching changes.

Code for onValue()
  • get(): If you need the data only once, you can use get() to get a snapshot of the data from the database. 

Code for get()

Default data types for Realtime Database

  • Boolean
  • Number
  • Object
  • String

Besides these mentioned data types no other data type is supported by realtime database. As for arrays it is stored as a key-value pair where the index is taken as the key.


Realtime database is very easy to use and effective for applications that require realtime functionality. But it has some disadvantages of its own. One such disadvantage is when we have to deal with highly nested datasets it becomes difficult to access the innermost nested data. 

For more detailed information refer to the documentation here.

Hope you find this blog useful.

Happy Learning!