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

如何在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

  1. sent_request is 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 empty sent_request array 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.
  2. Missing Null/Undefined Checks: If the user has no sent requests, item.val().sent_request could be null or undefined, 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 sentRequests exists 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 users table, you could also access the user directly with const user = Object.values(items.val())[0] instead of using forEach, but forEach remains safe if there's a chance of multiple matches (though you should enforce unique emails in your database rules).
  • If your sent_request structure is intentionally an array (uncommon in Firebase, as arrays are not recommended for dynamic collections), you can skip the Object.keys() step and use sentRequests directly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:41:25