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

在Cloud Function中用Node.js查询Firebase Realtime Database所有用户名

Hey there! Let's break down how to pull all usernames from Firebase Realtime Database using a Node.js Cloud Function—this mirrors your SQL SELECT usernames FROM TABLE request perfectly.

First, let's assume a common Realtime Database structure (adjust this to match your actual schema from the screenshot):

{
  "users": {
    "user_abc123": {
      "username": "sharjeel_malik",
      "email": "sharjeel@example.com"
    },
    "user_xyz789": {
      "username": "jane_doe",
      "email": "jane@example.com"
    }
  }
}
Step 1: Initialize Firebase Admin SDK

First, make sure your Cloud Functions project has the Firebase Admin SDK set up. If you're starting fresh, run firebase init functions to scaffold the project—this will add the necessary dependencies automatically.

Step 2: Write the Cloud Function

Here's a complete HTTP-triggered function that fetches all usernames and returns them as a list (just like your SQL query result):

const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Initialize the Admin SDK (only needs to run once)
admin.initializeApp();
const db = admin.database();

// HTTP-triggered function to get all usernames
exports.getAllUsernames = functions.https.onRequest(async (req, res) => {
  try {
    // Reference the "users" node in your database
    const usersRef = db.ref("users");
    // Fetch a one-time snapshot of the data
    const snapshot = await usersRef.once("value");

    // Handle case where no users exist
    if (!snapshot.exists()) {
      return res.status(404).json({ message: "No users found in the database" });
    }

    // Extract all username values into an array
    const usernames = [];
    snapshot.forEach((userSnapshot) => {
      const userData = userSnapshot.val();
      // Only add if the username field exists (avoid undefined entries)
      if (userData.username) {
        usernames.push(userData.username);
      }
    });

    // Return the list of usernames (matches your SQL single-column result)
    res.status(200).json({ usernames: usernames });
  } catch (error) {
    console.error("Error fetching usernames:", error);
    res.status(500).json({ error: "Failed to retrieve usernames" });
  }
});
Step 3: Deploy & Test
  1. Deploy the function with this command:
    firebase deploy --only functions:getAllUsernames
    
  2. Once deployed, you'll get a URL like https://us-central1-your-project.cloudfunctions.net/getAllUsernames—visit it in your browser or call it via POST/GET to see the list of usernames.
If Your Schema Is Different

If your usernames are stored directly under a node (e.g., /usernames where keys are usernames or values are usernames), you can simplify the code:

For example, if your DB looks like this:

{
  "usernames": [
    "sharjeel_malik",
    "jane_doe",
    "john_smith"
  ]
}

Or this:

{
  "usernames": {
    "id1": "sharjeel_malik",
    "id2": "jane_doe"
  }
}

You can replace the extraction part with:

const usernamesSnapshot = await db.ref("usernames").once("value");
const usernames = Array.isArray(usernamesSnapshot.val()) 
  ? usernamesSnapshot.val() 
  : Object.values(usernamesSnapshot.val());
Key Notes
  • Permissions: Make sure your Cloud Function service account has the Firebase Realtime Database Viewer role (or higher) in the Firebase Console's IAM section.
  • Large Datasets: If you have thousands of users, avoid fetching all data at once. Use limitToFirst()/limitToLast() with cursor-based pagination to handle large results efficiently.
  • Error Handling: The function includes basic error handling, but you can expand it to handle specific cases like missing permissions or invalid database paths.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:57:41