You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Cloud Function获取全量用户UID及批量更新数据库方案咨询

Got it, the problem here is that Firebase Auth's admin.auth().listUsers() only returns up to 1000 users per call by default—so you need to handle pagination to grab every user in your project. Let's fix that and make sure your batch update works reliably too.

Solution: Fetch All Firebase Auth Users with Pagination & Batch Update Realtime Database

First, we'll use Firebase Auth's built-in pagination support (via pageToken) to recursively fetch all users until there are no more pages left. Then, we'll handle the Realtime Database updates properly using Promise.all() to ensure all async operations complete before the function exits.

Here's the revised, production-ready code:

exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 20 * * *') 
  .timeZone('Asia/Seoul')
  .onRun(async (context) => {
    const allUserUids = [];
    let nextPageToken;

    // Recursive helper to fetch all users with pagination
    const fetchAllUsers = async () => {
      const userBatch = await admin.auth().listUsers(1000, nextPageToken);
      // Add UIDs from the current batch to our full list
      userBatch.users.forEach(userRecord => {
        allUserUids.push(userRecord.uid);
      });
      // If there's a next page, keep fetching
      if (userBatch.pageToken) {
        nextPageToken = userBatch.pageToken;
        await fetchAllUsers();
      }
    };

    try {
      // Step 1: Fetch every user in the project
      await fetchAllUsers();
      console.log(`Successfully fetched ${allUserUids.length} total user UIDs`);

      // Step 2: Prepare all database update promises
      const updateOperations = allUserUids.map(uid => {
        return db.ref(`Data/${uid}/Enter`).update({ test: 0, test2: 0 });
      });

      // Step 3: Wait for all updates to finish
      await Promise.all(updateOperations);
      console.log('All user records updated successfully');
      return null; // Signal successful completion to Cloud Functions
    } catch (error) {
      console.error('Failed to process users or updates:', error);
      throw error; // Let Cloud Functions log the error properly
    }
  });

Key Improvements Explained:

  • Async/Await Syntax: Replaced messy .then() chains with async/await for cleaner, easier-to-debug code.
  • Pagination Handling: The fetchAllUsers recursive function keeps pulling user batches until there are no more pages, ensuring you get every single UID.
  • Batch Update Efficiency: Using Promise.all() runs all database updates in parallel (instead of sequentially), which is faster and guarantees the function won't exit early before updates finish.
  • Consolidated Error Handling: A single try/catch block captures issues from both user fetching and database updates, making debugging simpler.

Quick Tips:

  • If you have 10,000+ users, consider adding a small delay (e.g., await new Promise(resolve => setTimeout(resolve, 100))) between pagination calls to avoid hitting rate limits, though Firebase Auth's listUsers() is optimized for most use cases.
  • Test this function with a small subset of users first to verify the update logic works as expected before running it against your full user base.

内容的提问来源于stack exchange,提问作者kwon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:37:44