I would like to query a Firebase Realtime Database to find a users account based on their Email.
Here is how I am doing it currently with the User's ID obviously wrong when you don't know the ID.
const userData = (await UsersDatabase.ref(`/Users/oi73WHp4T8LUCgtZzesN`).once('value')).val();
How can I query all of the users to find the account with a specific email.
Here is what the JSON Response looks like:
{
"userData":{
"Account Created":1647458347685,
"Date of Birth":"01/01/1901",
"Email":"[email protected]",
"Gender":"male",
"Name":"Test Account"
}
}
Here is the updated response from this request:
const userData = (await UsersDatabase.ref("Users").child("userData").orderByChild("Email").equalTo("[email protected]"));
Here is the response in Postman:
{
"userData": "https://domain.europe-west1.firebasedatabase.app/Users/userData"
}
All help is welcome!
CodePudding user response:
Assuming the email address is stored in the Email
property, you can use a query to find the correct child node of Users
with:
UsersDatabase
.ref("Users")
.orderByChild("Email")
.equalTo("[email protected]")
CodePudding user response:
In this line, you are awaiting the Reference
itself - not fetching its data:
const userData = (await UsersDatabase.ref("Users").child("userData").orderByChild("Email").equalTo("[email protected]"));
This line should be (fixed the query and shattered for readability):
const userData = (
await UsersDatabase.ref("Users")
.orderByChild("Email") // <-- removed .child("userData")
.equalTo("[email protected]")
.once('value') // <-- this was missing
).val();
/*
userData will be:
{
"oi73WHp4T8LUCgtZzesN": { // <- this will be random
"Account Created":1647458347685,
"Date of Birth":"01/01/1901",
"Email":"[email protected]",
"Gender":"male",
"Name":"Test Account"
}
}
*/
Although I would rewrite it like this to unwrap the data:
const foundUsersQuerySnapshot = await UsersDatabase.ref("Users")
.orderByChild("Email")
.equalTo("[email protected]")
.limitToFirst(1)
.once('value');
let userData = null;
foundUsersQuerySnapshot.forEach(childSnapshot => {
userData = { ...childSnapshot.val(), _key: childSnapshot.key };
return true; // <- only return first entry
});
/*
userData will either be null (not found) or:
{
"_key": "oi73WHp4T8LUCgtZzesN",
"Account Created":1647458347685,
"Date of Birth":"01/01/1901",
"Email":"[email protected]",
"Gender":"male",
"Name":"Test Account"
}
*/