1

I am trying to create a 1 to many data structure in firebase. My two objects look like this

category:
{
    cat1: { 
       name: 'Category 1'
    },
    cat2: {
       name: 'Category 2'
    }
}

products: 
{
   product1: {
     name: 'Product 1',
     categories: {
       cat1: true
     }
   },
   product2: {
     name: 'Product 2',
     categories: {
       cat1: true,
       cat2: true
     }
   }
}

Now how exactly would I query this data to get say product2 with all categories? I have tried this which gets me back the required data but it seems inefficient and doesn't match how the docs seem to suggest you do it....

    var ref = new Firebase("https://<my-firebase-url>/products/product2");
    var catRef = new Firebase("https://<my-firebase-url>/category");
    ref.once('value', function(snap) {
      var result = snap.val();
      Object.keys(result.categories).map(key => {
         catRef.child(key).once('value', function(category){
... //add category to array etc
         }
      }
    }

The docs suggest to use the child_added event but how does this make sense when I want the entire list not just when a child is added? (https://www.firebase.com/docs/web/guide/structuring-data.html):

    // List the names of all Mary's groups
var ref = new Firebase("https://docs-examples.firebaseio.com/web/org");
// fetch a list of Mary's groups
ref.child("users/mchen/groups").on('child_added', function(snapshot) {
  // for each group, fetch the name and print it
  String groupKey = snapshot.key();
  ref.child("groups/" + groupKey + "/name").once('value', function(snapshot) {
    System.out.println("Mary is a member of this group: " + snapshot.val());
  });
});
Community
  • 1
  • 1
Paul de Wit
  • 467
  • 1
  • 4
  • 17
  • The docs on firebase.com are now deprecated. Use the new website: firebase.google.com, regarding `child_added`, it not only retrieves the newly added child but also the existing childs. Have a look at the Firebase [upgrade guide](https://firebase.google.com/support/guides/firebase-web). – gegobyte Aug 15 '16 at 12:22
  • 1
    On the efficiency of the "looped loading". This is a common concerns of developers new to Firebase. But Firebase loads the items over a single connection and pipelines requests, so it's usually quite fast for reasonably sized data sets. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 for a longer explanation. – Frank van Puffelen Aug 15 '16 at 14:39

1 Answers1

3

To get all the categories that belong to product2, you should use:

firebase.database().ref('products/product2/categories').on('child_added', snapshot => {
    firebase.database().ref('category/'+snapshot.key).on('value', snap => {
        console.log(snap.val().name + ' belongs to product2'); //Will print Category 1 and Category 2
    });
}):
gegobyte
  • 4,945
  • 10
  • 46
  • 76