What is the response structure of firebase queries? Is there any documentation? I couldn't find anything. I don't why user is null below. Do I need to run for loop and get the first item?
const result = await firebase.child('users').orderByChild('email')
.equalTo(memberEmail).limitToFirst(1)
.once('value');
const user = result.val();
the following code works, but I don't want to run a loop to get single value. How do I get the user without running a loop?
result.forEach((value) => {
alert(`user = ${JSON.stringify(value.val())}`);
});
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. So if you use a query, you will always need a loop.
The way to not require a loop is by directly accessing the child node that you are looking for. In your current data structure you likely store the users by their uid, so you can only access them directly by uid:
const result = await firebase.child('users').child(currentUser.uid).once('value');
const user = result.val();
If you'd store the users by their email address (you'll have to encode it, since a .
cannot be used in the key), you could also access the users by their email address.
An idiomatic way to do this with Firebase is to keep a separate node that maps email addresses to uids. You'd then do two direct lookups:
firebase.child('emailToUid').child(email)
firebase.child('users').child(uid)
Each of those would return a single node (or no node if there is no match found), so you could chain the awaits and won't need a loop
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments