Depetrify
Depetrify

Reputation: 175

Querying all parents and their children Firebase

I'm basically trying to list userIDs 1 at a time and also their children elements (firstname, last name, email , picture) so basically i want userid--> firstname,lastname,emailpicture looped for every user . this seems very difficult to do in firebase.

layout of firebase ( i cannot change this ) : https://i.sstatic.net/tLEZi.png

I'm not understanding how to grab all of the parents dynamically since they have randomly generated id's. i can do it one by one but i need to do it dynamically every time a user is added. Below is an example of what i want to do for each , but im manually inputting the ID so its pretty irrelevant.

var database = firebase.database();

database.ref().once('value', function (data) {
picture = data.child("4320552453").child('picture').val();
firstName = data.child("4320552453").child('firstname').val();
lastName = data.child("4320552453").child('lastname').val();
email = data.child("4320552453").child('email').val();

$('#image').html('<img src="' + picture + '">')
$('#image').append(firstName)
$('#image').append(lastName)
$('#image').append(email)
my end goal is something like
div 1 userid 1 -> all information1 for each user
div 2 userid 2 -> all information  for each user
div 3 userid  3-> all information  for each user

Upvotes: 0

Views: 25

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

If you want to loop over all child nodes in a DataSnapshot, use DataSnapshot.forEach. So:

database.ref().once('value', function (snapshot) {
  snapshot.forEach(function(child) {
    picture = child.child('picture').val();
    firstName = child.child('firstname').val();
    lastName = child.child('lastname').val();
    email = child.child('email').val();
    console.log(snapshot.key, email, firstName, lastName, picture);
  });
});

Upvotes: 0

Related Questions