Skip to content
Advertisement

Firebase Cloud Function listUser get 1000+ users

exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 20 * * *')
    .timeZone('Asia/Seoul') // Users can choose timezone - default is America/Los_Angeles
    .onRun((context) =>
    {
        var allUsers = [];
        return admin.auth().listUsers()
            .then(function (listUsersResult)
            {
                listUsersResult.users.forEach(function (userRecord)
                {
                    // For each user
                    var userData = userRecord.toJSON();
                    allUsers.push(userData.uid);
                    console.log(allUsers);
                });
                //res.status(200).send(JSON.stringify(allUsers));

            }).then(function ()
            {
                allUsers.forEach(function (elem)
                {
                    db.ref(`Data/${elem}/Enter`).update({ test: 0, test2: 0 });
                });
            })
            .catch(function (error)
            {
                console.log("Error listing users:", error);
                //res.status(500).send(error);
            });

    });

I want to modify the database value that has the uid of all users as the key after getting uid through listUser(), but listUser() has 1000 max. If there is a good way to get uid of all users, please let me know

Advertisement

Answer

The Firebase Admin SDK supports pagination to cycle through all the registered user accounts. Follow the instructions in the documentation. You will need to use the API to cycle through batches of 1000 or less. The code sample provided in the documentation illustrates this:

function listAllUsers(nextPageToken) {
  // List batch of users, 1000 at a time.
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch(function(error) {
      console.log('Error listing users:', error);
    });
}
// Start listing users from the beginning, 1000 at a time.
listAllUsers();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement