如何在Firebase中从父节点获取所有子节点?适配多用户场景
Retrieve List of Society Names from Current User's
societies Node in Firebase Here's a straightforward, user-adaptable approach to fetch the list of society names (like ALT5, ASN11, Foot15) from the societies node under the current user's entry in Firebase Realtime Database:
Step 1: Grab the Current User's UID
First, get the authenticated user's unique ID with Firebase Auth. Don't forget to handle cases where the user might not be logged in yet:
// Fetch current user's UID, with optional chaining to avoid errors const runUid = firebase.auth().currentUser?.uid; if (!runUid) { console.error("Error: User is not logged in!"); return; }
Step 2: Point to the User's societies Node
Create a database reference that targets the societies node specifically for the logged-in user:
// Reference the societies node under the current user's UID const societiesRef = firebase.database().ref(`sUsers/${runUid}/societies`);
Step 3: Fetch and Extract Society Names
Use a value listener to pull the data, then extract the child node names (which are the keys of the societies object) using Object.keys():
// Fetch the societies data and extract the names societiesRef.once('value') .then(snapshot => { if (snapshot.exists()) { // Get the list of society names (the keys of the societies node) const societyNames = Object.keys(snapshot.val()); console.log("User's societies:", societyNames); // Use this list however you need—render in UI, store in state, etc. } else { console.log("No societies found for this user."); } }) .catch(error => { console.error("Failed to fetch societies:", error); });
Why This Works for All Users
- Since we use the current user's UID to build the database path, this code automatically targets their unique
societiesnode—regardless of what child nodes (like ALT5, ASN11, or custom ones for other users) exist under it. - If you need real-time updates (e.g., when a new society is added for the user), swap
once('value')withon('value')to listen for ongoing changes.
内容的提问来源于stack exchange,提问作者shaddles
相关产品推荐
相关产品推荐

