mattymue
mattymue

Reputation: 15

Firebase JS: Database call to iterate over nested data

I am using Firebase Realtime DB. There is a list of 'users' at the top level and each user has a list of books. I am trying to iterate to get all the books from all users but I am having an issue using the firebase db call to do so. I am trying to do so with the following but I believe I am doing something wrong in this call to achieve what I am going after.

firebase.database().ref('/').on('value', (snapshot) => {
    snapshot.forEach((child) => {
        console.log(child.child('books').val());
    });
})

screenshot of DB structure

Upvotes: 1

Views: 451

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Right now you're reading the root node, and then iterating over its child nodes. That means that child is a snapshot of the key and value of the users node, not of the child nodes under that. You can easily verify that by logging the key of the child node:

firebase.database().ref('/').on('value', (snapshot) => {
  snapshot.forEach((child) => {
    console.log(child.key);
  });
})

This will log:

users

And since the users node does not have a books property, the child.child('books').val() is null.


There are two possible solutions:

  1. Read only the data under the users node, which you do with:

    firebase.database().ref('/users').on('value', (snapshot) => {
      snapshot.forEach((user) => {
        console.log(user.child('books').val());
      });
    })
    
  2. Handle the users node in your callback, with something like:

    firebase.database().ref('/').on('value', (snapshot) => {
      snapshot.child('users').forEach((user) => {
        console.log(user.child('books').val());
      });
    })
    

In either case you'll likely also want to iterate over the books, so will need a/another nested loop. Something like:

firebase.database().ref('/users').on('value', (snapshot) => {
  snapshot.forEach((user) => {
    snapshot.child('books').forEach((book) => {
      console.log(book.val());
      // or: console.log(book.child('author').val());
    });
  });
})

Upvotes: 1

Related Questions