Firebase total user count

后端 未结 3 1132
难免孤独
难免孤独 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('/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('');
    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('/userCount');
    ref.on('value', function(snap) {
      console.log(snap.val());
    });
    

提交回复
热议问题