Web应用中基于JavaScript从Firebase数据库检索值求助
addresses Node Hey there! Let's work through how to properly check if a specific user UID exists under your addresses node. Looking at your current code, you're on the right track with the query, but there are a few tweaks to get the result you need.
First: Understand the Current Issue
Your code uses orderByChild("uid").equalTo(user.uid) which is correct for filtering entries by UID, but when you log snapshot.key, you're actually getting the key of the parent addresses node, not any matching child entries. To properly check for existence, we need to use Firebase's snapshot.exists() method.
Solution 1: Using Your Existing Data Structure
If you're keeping addresses as a list of entries where each has a uid field, here's the corrected code to check for existence and access the matching data:
var refAdd = firebase.database().ref().child('addresses'); // Query for entries where uid matches the user's UID refAdd.orderByChild("uid").equalTo(user.uid).once("value") .then(function(snapshot) { if (snapshot.exists()) { console.log(`Found address(es) for UID: ${user.uid}`); // Iterate through all matching address entries snapshot.forEach(function(childSnapshot) { var address = childSnapshot.val(); var addressKey = childSnapshot.key; console.log(`Address key: ${addressKey}, Data:`, address); }); } else { console.log(`No address found for UID: ${user.uid}`); } }) .catch(function(error) { console.error("Error checking address:", error); });
Key Notes for This Approach:
snapshot.exists()returnstrueif there are any matching child entries,falseotherwise.- Don't forget to add an index! In your Firebase Console, go to the Realtime Database Rules tab and add an index for the
uidfield underaddressesto avoid performance warnings:{ "rules": { "addresses": { ".indexOn": "uid" } } }
Solution 2: Optimize Your Data Structure (Recommended)
If each user only has one address (or you want to map UIDs directly to addresses), consider restructuring your addresses node to use UIDs as child keys. This makes the query O(1) (instant) instead of requiring a filter:
// Directly reference the address node for the user's UID var refAdd = firebase.database().ref().child('addresses').child(user.uid); refAdd.once("value") .then(function(snapshot) { if (snapshot.exists()) { console.log(`Address found for UID: ${user.uid}`, snapshot.val()); } else { console.log(`No address found for UID: ${user.uid}`); } }) .catch(function(error) { console.error("Error checking address:", error); });
This structure would look like this in your database:
addresses |- userUid1 |- street: "123 Main St" |- city: "Anytown" |- userUid2 |- street: "456 Oak Ave" |- city: "Somecity"
It's much more efficient because you're directly accessing the exact node you need, no filtering required.
内容的提问来源于stack exchange,提问作者Dawesy

