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());
});
});