Firebase Database reading data


#1

I get a snapshot from Firebase database as follows:

firebase.database().ref('/explore/').once('value', (snapshot) => {

});

snapshot is an object with several levels:

user ID1 (“123123123”)

  • name
  • age
  • ID
    User ID2 (“234235235”)
  • name
  • age
  • ID
    And so no…

I need to display in a list all of the "name"s of all of the users. And I don’t have the ID’s of all of the users (except in the Database). I can’t get my head around to using a for loop to loop through all the available users (ID’s). Any help will be greatly appreciated!


#2

You should be able to do something like this to get everything in an array.

firebase.database().ref('/explore/').once('value', (snapshot) => {
  let users = [];
  snapshot.forEach( snap => {
    users.push(snap.val()); //or snap.val().name if you just want the name and not the whole object
  });
});

#3

Thanks! I’m still getting this error:


#4

And 10 hours later, here is the solution:

let users = [];
   snapshot.forEach(snap => {
     users.push(snap.val()); //or snap.val().name if you just want the name and not the whole object
     return false;   //<=THIS IS WHAT WAS MISSING!!!!!
   });