0

In firebase I am trying to create and access a database ref of a child node that has a "push" ID in the middle of the path. I want to get to the name: "Cooking area" which is inside a department (dept1) which is inside "depts". The problem is that "depts" is inside a database reference that is randomly generated by firebase (the push ID).
My question is: how can I get to the references inside that L3s_dBCdKN4EyRJAi?

firebase structure

export const firebaseApp = Firebase.initializeApp(config);
export const db = firebaseApp.database();

export const spacesRef = db.ref('spaces'); // this WORKS

export const deptsRef = spacesRef.child('depts'); // this DOESN'T!!!

1 Answers1

1

The short answer is you can't, not without querying all your 'spaces'. Chances are when you hit a problem like this you should rethink you data structure. Firebase encourages you to Avoid Nested Data. So rather than having a depts tree under your space you could have a depts tree at your root (with children of the same id as your space) so you can more easily use it as a reference.

{
    "spaces": {
        "L3s__dBCdKN4EyRJfAi": {
            "address": "...",
            "comments": "...",
            "name": "..."
        }
    },
    depts: {
        "L3s__dBCdKN4EyRJfAi": {
            "dept1": {
                "name": "...",
                "numberOfRooms": "..."
            }
        }
    }
}
Chris Edgington
  • 2,937
  • 5
  • 23
  • 42
  • Thanks @Chris, but if the "spaces" themselves (as well as the the "depts") have randomly generated push IDs how can we relate them? – Joao Alves Marrucho Jan 30 '18 at 12:24
  • The way Firebase recommend is to use the ID of the spaces child. I've updated my answer with the data structure you could use. – Chris Edgington Jan 30 '18 at 12:55
  • Thanks again Chris. I have marked your answer as correct and I have created a different question. I would really appreciate your help there: https://stackoverflow.com/questions/48523733/how-to-establish-the-relation-between-two-different-trees-in-the-root-of-the-dat – Joao Alves Marrucho Jan 30 '18 at 14:27