简体   繁体   中英

Getting all collections data from Firebase in the right way

I've something like the following scheme in my firebase realtime database:

{
  "x" : {
    "-MTBDnGW-d5m35cmcoDU" : {},
    "-MTBEH4CpIqVcD-ffeJC" : {}
  },
  "y" : {
    "-MTCaxkppXKi6eS8R7zA" : {}
  },
  "users" : {
    "-MTBCUv6ewdVsLMan06a" : {
      "name" : "xxxx",
      "pin" : "x"
    },
    "-MTCYk2M16QiFwXrvb2_" : {
      "name" : "yyyy",
      "pin" : "y"
    }
  }
}

My idea is to get the data from my code with something like this code to sum all the entries for each collection, reading each name from the 'users' collection and using them to count in their respective collection, like x and y in this example.

usersColection.orderByChild('name').on('child_added',function(snapshot){
    var pin = snapshot.child('pin').val();
    var actives = 0; //Restart for each 'user'
    var pinCollection= db.ref().child(pin);
    pinCollection.orderByChild('name').limitToLast(20).on('child_added', function(snapshot){
        actives++; //Sum active users in the last 20 registers
    });
    console.log(pin,actives); //Print pin and the amount of active users for that pin name
});

But for me this doesn't like the proper way to do it because it is async and do not iterate between the pin names as i want. My expected output should be something like this, but it's not working with the code from above:

Pin x active entries: 2
Pin y active entries: 1

Thanks in advance.

The problem is that your console.log(pin,actives) runs before any of the actives++ has been called. Data is loaded from Firebase asynchronously, and any code that needs the data needs to be inside the callback that gets executed once the data is available.

So one solution is this:

usersColection.orderByChild('name').on('child_added',function(snapshot){
  var pin = snapshot.child('pin').val();
  var pinCollection= db.ref().child(pin);
        
  pinCollection.orderByChild('name').limitToLast(20).once('value')then((snapshot) => {
        let actives = value.numChildren()
        console.log(pin,actives);
    });
});

You might need to use Promise.all() to wait for all pins to be loaded, so I recommend getting comfortable with promises as a way to handle asynchronous data loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM