Reputation: 5
I'm trying to query a Firebase Realtime Database to retrieve a specific user based on their email using JavaScript. I want to use the equalTo and orderByChild methods together in my query, but I'm encountering issues. Here's the code snippet I have:
const usersRef = ref(database, 'users');
const userEmail = "[email protected]";
const query = query(usersRef, orderByChild('email'), equalTo(userEmail));
emailQuery.on('value', (snapshot) => {
if (snapshot.exists()) {
// The user with the email address `userEmail` was found.
const user = snapshot.val();
console.log(user)
} else {
// The user with the email address `userEmail` was not found.
}
});
However, when I run this code, I get an error indicating that emailQuery.on is not defined. It seems that I cannot use on() directly within the query function.
Sign-in error: emailQuery.on is not a function
How can I define "on()"? How can I modify my code to achieve my desired functionality?
I already tried other functions like once or forEach but they seem to provide the same error.
I've also tried this code:
const usersRef = ref(database, 'users');
console.log(usersRef);
usersRef.orderByChild('email').equalTo(userEmail)
.once('value').then((snapshot) => {
const userObject = snapshot.val();
console.log(userObject);
})
but it just provides me this error:
Sign-in error: usersRef.orderByChild is not a function
Upvotes: 0
Views: 128
Reputation: 598668
You're mixing SDK versions/syntaxes.
This line uses the modular syntax introduced in SDK version 9:
const query = query(usersRef, orderByChild('email'), equalTo(userEmail));
But in this line you then try to use the namespaced API calls that have always existed:
emailQuery.on('value', (snapshot) => {
While both syntaxes continue to be supported, you can't use mix and match them at will. In a single file you will have to use one or the other.
The equivalent of ref.on(...)
in the modular syntax, is the global onValue
function as shown in the Firebase documentation on listening for value events.
Based on that, you'd need:
onValue(emailQuery, (snapshot) => {
...
});
Upvotes: 0