Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing nested data in Firebase

I am having trouble getting the correct data in my web app from Firebase.

The problem is that the data I want in a object named 'random number'. I want to be able to bring all my fields into variables so I can test, set up my page to display all the data, that sort of thing. But I am lost on how to query these keys in order to use them.

database

Right now I am just logging the data to the console to get a feel for the data structure. PS. I didn't organize the data, someone did it before me.

code

Where I have the two commented out variables with I had tried to even type in one of the key's to see if I could get the data but it does not work.

like image 517
John Bull Avatar asked Dec 31 '25 15:12

John Bull


1 Answers

If you are retrieving everything under the inspectors, you can access the data like this:

firebase
  .database()
  .ref()
  .child('inspectors')
  .once('value', function (inspectorsSnapshot) {

    inspectorsSnapshot
      .child('obfuscated') // This key is obfuscated in your question.
      .child('openTickets')
      .forEach(function (openTicketSnapshot) {
        console.log(openTicketSnapshot.key); // The random key.
        var val = openTicketSnapshot.val();
        console.log(val.address);
        console.log(val.assignedInspector);
        // etc.
      });
  });

You can also refine the query itself to retrieve only the data you want:

firebase
  .database()
  .ref()
  .child('inspectors')
  .child('obfuscated') // This key is obfuscated in your question.
  .child('openTickets')
  .once('value', function (openTicketsSnapshot) {

    openTicketsSnapshot.forEach(function (openTicketSnapshot) {
      console.log(openTicketSnapshot.key); // The random key.
      var val = openTicketSnapshot.val();
      console.log(val.address);
      console.log(val.assignedInspector);
      // etc.
    });
  });

And, if you only want the first few entries:

firebase
  .database()
  .ref()
  .child('inspectors')
  .child('obfuscated') // This key is obfuscated in your question.
  .child('openTickets')
  .limitToFirst(10)
  .once( ... // etc.
like image 106
cartant Avatar answered Jan 03 '26 13:01

cartant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!