How to retrieve data from Firebase Database?

gegobyte picture gegobyte · Jul 23, 2016 · Viewed 78.8k times · Source

I'm trying to create a simple program that takes name, mobile number and email address from user and then puts the data on Firebase Realtime Database.

There are 3 input boxes and a button which on click does the above operation. Here is the code:

<input type="text" id="name">
<input type="text" id="mobile">
<input type="text" id="email">

<button type="button" id="button" onclick="addLead()">Submit</button>

I've set up Firebase like this:

<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    ...
  };
  firebase.initializeApp(config);

  var database = firebase.database();
</script>

And here is my addLead() function:

function addLead() {
    var clientName = document.getElementById('name').value;
    var clientMobile = document.getElementById('mobile').value;
    var clientEmail = document.getElementById('email').value;

    var newClientKey = database.ref().child('leads').push().key;
    database.ref('leads/'+newClientKey+'/name').set(clientName);
    database.ref('leads/'+newClientKey+'/mobile').set(clientMobile);
    database.ref('leads/'+newClientKey+'/email').set(clientEmail);
}

This is how I put data to database which works.

enter image description here

So the newClientKey is generating some string, it works well when inserting but now how to retrieve? The official documentation is of no help. This generated string might be based on timestamp, if that's the case then generating it again would be impossible.

When retrieving how will I get access to email, mobile and name under that uniquely generated string which was only available at the time of inserting?

Going by the above structure, I need to get 2 levels down to access the required data and because of the lack of documentation, I don't know how to do that, I'm not sure if something like this will work:

database.child().child();

Answer

gegobyte picture gegobyte · Jul 25, 2016

The answer to this question is buried deep within Firebase Database Reference. forEach() is used to get to the child without knowing the child's exact path.

var leadsRef = database.ref('leads');
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
    });
});

Now childSnapshot will contain the required data, the same thing can also be accessed using child_added.

leadsRef.on('child_added', function(snapshot) {
      //Do something with the data
});

The only difference is that in case of forEach(), it will loop through from the start so if any new data will be added, it will also load the previous data but in case of child_added, the listener is only on new child and not the previous existing childs.