How to retrieve data from Firebase Database?

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.


You could also use dot notation to get the value of the child you are looking for for.

Below I just commented out the forEach loop from the highest rated answer and added a console.log().

 var leadsRef = database.ref('leads');
  leadsRef.on('value', function(snapshot) {
      // snapshot.forEach(function(childSnapshot) {
        var childData = snapshot.node_.children_.root_.value.value_;
        console.log("snapshot.node_.children_.root_.value.value_: ", snapshot.node_.children_.root_.value.value_)
      // });
  });

At the time of posting this I am using firebase 5.9.1

src="https://www.gstatic.com/firebasejs/5.9.1/firebase.js"


var reference = db.ref('/test/');
reference.on('value', function(snapshot) {
snapshot.forEach(function(userSnapshot){
console.log(userSnapshot.val().url)
document.getElementById('gmap').href = userSnapshot.val().location;
document.getElementById('gimg2').src = userSnapshot.val().url;
document.getElementById('name').innerHTML = userSnapshot.val().uid;

I was facing the same issue. I wanted to read the data from the firebase realtime database and print the same on the web. The data I am reading is in the test document. Use the on() function to take the snapshot of it. Firebase provides you with a foreach loop to iterate over the data in the test document. The variable userSnapshot reads the value while looping. The variables location, url, uid are the keys in the test document.

document.getElementById('gmap').href
document.getElementById('gimg2').src 
document.getElementById('name').innerHTML

are the DOM element to print the data on the web

<a id="gmap" class="btn btn-success btn-sm float-right" type="button" 
 role="button">See location </a>
 <p id="name"></p>
 <img id="gimg2" class="img-fluid"/>

I hope this helps someone.