Firebase total user count

Süha Boncukçu picture Süha Boncukçu · Dec 4, 2015 · Viewed 10k times · Source

Is there a way to get all the users' count in firebase? (authenticated via password, facebook, twitter, etc.) Total of all social and email&password authenticated users.

Answer

David East picture David East · Dec 4, 2015

There's no built-in method to do get the total user count.

You can keep an index of userIds and pull them down and count them. However, that would require downloading all of the data to get a count.

{
  "userIds": {
    "user_one": true,
    "user_two": true,
    "user_three": true 
  }
}

Then when downloading the data you can call snapshot.numChildren():

var ref = new Firebase('<my-firebase-app>/userIds');
ref.once('value', function(snap) {
  console.log(snap.numChildren());
});

If you don't want to download the data, you can maintain a total count using transactions.

var ref = new Firebase('<my-firebase-app>');
ref.createUser({ email: '', password: '', function() {
  var userCountRef = ref.child('userCount');
  userCountRef.transaction(function (current_value) {
    // increment the user count by one
    return (current_value || 0) + 1;
  });
});

Then you can listen for users in realtime:

var ref = new Firebase('<my-firebase-app>/userCount');
ref.on('value', function(snap) {
  console.log(snap.val());
});