Firebase total user count

后端 未结 3 1120
难免孤独
难免孤独 2020-12-31 20:59

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

相关标签:
3条回答
  • 2020-12-31 21:36

    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());
    });
    
    0 讨论(0)
  • 2020-12-31 21:36

    Using Cloud Functions:

    exports.updateUserCount = functions.auth.user().onCreate(user => {
      return admin.database().ref('userCount').transaction(userCount => (userCount || 0) + 1);
    });
    

    Just note that a Cloud Functions event is not triggered when a user is created using custom tokens. In that case, you would need to do something like this:

    exports.updateUserCount = functions.database.ref('users/{userId}').onCreate(() => {
      return admin.database().ref('userCount').transaction(userCount => (userCount || 0) + 1);
    });
    
    0 讨论(0)
  • 2020-12-31 21:58

    Here is a javascript Module for this purpose - https://gist.github.com/ajaxray/17d6ec5107d2f816cc8a284ce4d7242e

    In single line, what it does is -

    Keep list (and count) of online users in a Firebase web app - by isolated rooms or globally

    For counting all users using this module -

    firebase.initializeApp({...});
    var onlineUsers = new Gathering(firebase.database());
    gathering.join();
    
    // Attach a callback function to track updates
    // That function will be called (with the user count and array of users) every time user list updated
    gathering.onUpdated(function(count, users) {
        // Do whatever you want
    });
    
    0 讨论(0)
提交回复
热议问题