Read and Write operation from firebase database

Posted By :Arun Singh |28th November 2018

Get a database reference :

This blog covers the basics of retrieving operation from firebase database. you have to need an instance of firebase database reference.

// Retrieve a reference to the database service var database = firebase.database();

Reading and writing data:

The document written covers all the basics for the retrieval of data and the procedure to order and filter the firebase  data.
The retrieval of the data from the firebase is done by attaching an asynchronous listener to the firebase.database.Reference.
When the data is in its initial state the listener is triggered only once and again when there is a change in the data.

Basic write operations:

For the very  basic write operations, we can use set() to save data to a specified reference, replacing any existing data at that path.

function writeUserData(userId, name, email, imageUrl) {  firebase.database().ref('users/' + userId).set({    username: name,    email: email,    profile_picture : imageUrl  }); }

Using the set() overwrites the data at specified location, including any of the child nodes.

Listen for value events

For reading the data at the path and listen for changes, you can use the on() or once() methods of firebase.database.Reference to observe the events.

example retrieving the star count of a post from the database: 

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount'); starCountRef.on('value', function(snapshot) {  updateStarCount(postElement, snapshot.val()); });

Read data once:

When the UI element you don't want to  change you may sometime have a snapshot of your data without listening for the changes.One can use the method called once() to simplify the scenario.

var userId = firebase.auth().currentUser.uid; return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {  var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';  // ... });

Updating or deleting data:

Update specific fields
The update() method is used to simultaneously write children of nodes without overwriting.
A path for the key is used when calling the update() function. 

function writeNewPost(uid, username, picture, title, body) {  // A post entry.  var postData = {    author: username,    uid: uid,    body: body,    title: title,    starCount: 0,    authorPic: picture  };  // Get a key for a new Post.  var newPostKey = firebase.database().ref().child('posts').push().key;  // Write the new post's data in both the posts list and the user's post list. and the user's post list.  var updates = {};  updates['/posts/' + newPostKey] = postData;  updates['/user-posts/' + uid + '/' + newPostKey] = postData;  return firebase.database().ref().update(updates); }

Add a Completion Callback:

To make sure about your data is committed or not a completion callback can be added.Set() and update() both are used for the completion is called only when the write is committed to the database.Callback passes an error if the call  is unsuccessful.

  firebase.database().ref('users/' + userId).set({    username: name,    email: email,    profile_picture : imageUrl  }, function(error) {    if (error) {      // The write failed...    } else {      // Data saved successfully!    }  }); }

Delete data:

The easiest form of deleting data from the location is to use remove().
For some of the write operations like set() and update() we can delete by specifying null as the value.


Detach listeners:

You can remove the callbacks by calling off() method on  Firebase database reference.

Write data offline:

The app remains  active even there is  issue related network latency or connectivity,this is because the client on the firebase have  its own internal version of active data,because when the data is written first it is written to the local version and this results  all writes to  database immediately trigger the local events.



About Author

Arun Singh

Arun is a MEAN stack developer. He has a fastest and efficient way of problem solving techniques. He is very good in JavaScript and also have a little bit knowledge of Java and Python.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us