如何在Firebase中遍历子记录?获取users表sent_request的user_keys
Fixing Firebase Realtime Database sent_request Retrieval
It looks like you're trying to fetch the sent_request child nodes for a specific user but aren't getting the expected output. Let's break down what might be going wrong and how to fix it.
Common Issues in Your Current Code
sent_requestis an Object, Not an Array: Firebase Realtime Database stores collections as objects (with auto-generated or custom keys) rather than arrays. Your current code overwrites the emptysent_requestarray with this object, but logging it directly might not display the user keys in a readable format, or you may not be explicitly extracting the keys you need.- Missing Null/Undefined Checks: If the user has no sent requests,
item.val().sent_requestcould benullorundefined, leading to unexpected behavior or errors.
Corrected Code
Here's an updated version of your function that addresses these issues and properly extracts the user keys from sent_request:
getProfileData(emailID) { const ref = firebase.database().ref('users'); ref.orderByChild("email").equalTo(emailID).once("value", (items) => { let sentRequestKeys = []; items.forEach((item) => { const sentRequests = item.val().sent_request; // Check if sent_request exists and is an object before processing if (sentRequests && typeof sentRequests === 'object') { // Convert the Firebase object into an array of user keys sentRequestKeys = Object.keys(sentRequests); // If you need access to the values associated with each key too, use this: // const sentRequestDetails = Object.entries(sentRequests); // sentRequestDetails.forEach(([key, value]) => { // console.log(`User Key: ${key}, Request Data:`, value); // }); } }); console.log("Sent Request User Keys:", sentRequestKeys); }).catch((error) => { // Handle any database query errors (e.g., permission issues) console.error("Error fetching profile data:", error); }); }
Key Improvements
- Explicit Key Extraction: Using
Object.keys(sentRequests)converts the Firebase collection object into an array of user keys, which is likely what you're expecting to see. - Null Safety: We add checks to ensure
sentRequestsexists and is an object before processing, preventing runtime errors. - Error Handling: Added a
.catch()block to log any issues that occur during the database query (like invalid permissions or incorrect paths). - Readability: Renamed variables for clarity and added comments to explain each step.
Additional Notes
- Since email addresses should be unique in your
userstable, you could also access the user directly withconst user = Object.values(items.val())[0]instead of usingforEach, butforEachremains safe if there's a chance of multiple matches (though you should enforce unique emails in your database rules). - If your
sent_requeststructure is intentionally an array (uncommon in Firebase, as arrays are not recommended for dynamic collections), you can skip theObject.keys()step and usesentRequestsdirectly.
内容的提问来源于stack exchange,提问作者Shreyas Pednekar
相关产品推荐
相关产品推荐

