Home > Software engineering >  How can I navigate children in Firebase?
How can I navigate children in Firebase?

Time:01-17

I am using Firebase Realtime Database. I have some keys in the root. And I have keys and children within these keys. I need to listen to the values of a specific child. For example, the structure is like this:

root
├── d775810
│   ├── datas_for_type
│   │   └── timestamp
│   │       └── multiple list datas  
│   └── reportFlag 
│       └── timestamp
│           └── flagAnnotation:True
└── a413ba21
    ├── datas_for_type
    │   └── timestamp
    │       └── multiple list datas 
    └── reportFlag 
        └── timestamp
            └── flagAnnotation:False

I need to listen to the "flagAnnotation" child. If it is true, I will access the data with the same timestamp and create a PDF. How can I listen to the values of this child?

I tried this:

dbRef.ref().on("child_added", (snapshot) => {
    console.log(`Child added: ${snapshot.key}`);
});

This give only d775810,a413ba21.. and if ı add root, ıt will give them.

CodePudding user response:

Firebase Realtime Database reads always return full nodes. This means that you can't listen for just the flagAnnotation properties.

You can listen for the entire JSON branch however, and then navigate the data snapshot you get to just show the flagAnnotation values.

firebase.database().ref().get('value').then((rootSnapshot) => {
  rootSnapshot.forEach((childSnapshot) => {
    console.log(childSnapshot.val().reportFlag.timestamp.flagAnnotation);
  });
})

If the timestamp in your JSON is dynamic, you'll need another forEach to loop over those children, and it'd become:

firebase.database().ref().get('value').then((rootSnapshot) => {
  rootSnapshot.forEach((childSnapshot) => {
    const reportFlagSnapshot = childSnapshot.child('reportFlag');
    reportFlagSnapshot.forEach((timestampSnapshot) => {
      console.log(timestampSnapshot.key, timestampSnapshot.val().flagAnnotation);
    })
  });
})
  • Related