Firebase中snapshot.val()返回null,为何无法定位正确集合?
Hey there! Let's work through this problem step by step—this is a super common pitfall when getting started with Firebase Realtime Database, so don't worry about it being a "low-level mistake" at all.
Core Issue Breakdown
The error Cannot read property 'userControl' of null happens because snapshot.val() is returning null—meaning your database reference isn't pointing to an existing node in your database. When you try to access a property on null, JavaScript throws that TypeError.
Let's Fix the Path First
Looking at your database structure, the nodes under /users are Firebase Auth user UIDs (those long random strings), not the modified email address samgmailcom you're using in your code. That's the most likely reason your reference is returning no data!
Firebase best practice is to use the authenticated user's UID as the key for their user data, since it's unique and directly tied to their auth session. Here's how to adjust your code:
if(firebase.auth().currentUser){ // Grab the logged-in user's unique UID const userId = firebase.auth().currentUser.uid; // Reference the user's node using their UID return firebase.database().ref(`/users/${userId}`).once('value').then((snapshot) => { console.log("User data:", snapshot.val()); // Always check if the snapshot exists before accessing properties if(snapshot.exists()){ console.log("User control value:", snapshot.val().userControl); this.user = snapshot.val(); // Assign data to your component's user property } else { console.log("No user data found in the database for this account"); this.user = null; } }).catch(error => { // Handle any errors that occur during the read console.error("Error fetching user data:", error); this.user = null; }); } else { this.user = null; }
Additional Checks to Ensure Success
Verify Database Security Rules
Make sure your Realtime Database rules allow the logged-in user to read their own data. A common secure rule set for user data looks like this:{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }If your rules are set to
".read": truetemporarily (for testing), that's okay—but always lock them down for production!Confirm the User Node Exists
Double-check in your Firebase Console's Realtime Database panel that the node/users/[your-user-uid]actually exists, and that it contains theuserControlfield. It's easy to accidentally create data under the wrong path!Handle Asynchronous Logic Properly
Since database reads are asynchronous, make sure you're not trying to usethis.userbefore the Promise resolves. In Vue, you might want to wrap this code in anasync/awaitfunction or use a loading state until the data is fetched.
内容的提问来源于stack exchange,提问作者Samuel M. Bednarz

