I’m experiencing an issue while trying to query my Firebase Realtime Database using the equalTo() function. When I log snapshot.val(), it returns null instead of the expected result. I’m unsure what’s causing this problem and would appreciate any insights or suggestions.
Here’s a simplified version of my code:
import { ref, getDatabase, query, equalTo, get } from "firebase/database";
const database = getDatabase();
const codesRef = ref(database, 'codes');
const queryRef = query(codesRef, equalTo('-NZEG-Ie9TKAdBmqw3Oc'));
get(queryRef)
.then((snapshot) => {
console.log(snapshot.val()); // Returns null instead of the expected result
})
.catch((error) => {
console.log('Error:', error);
});
My codes structure in the database looks like this:
"codes": {
"DNdttBf": "-NZBEdJiIs-05n3xW81P",
"HPFfOS92p": "-NZEG-Ie9TKAdBmqw3Oc",
"gzstxNSHK": "-NZFo-0FZEB7GU0EpZau",
"rLp2S98kx": "-NZENEaUYiaZCN2czfWj"
},
I expect the query to retrieve the code -NZEG-Ie9TKAdBmqw3Oc based on the key HPFfOS92p, but it returns null instead.
I’ve double-checked the value I’m passing to equalTo() and verified that it matches the value in the database. I’m not sure what else could be causing this issue.
Any suggestions or insights into what might be causing the problem would be greatly appreciated. Thank you!
2
Answers
Firebase Realtime Database queries consist of multiple parts:
While you do have part 2 in your query, you’re missing an instruction to order the data.
To fix this, include an
orderBy...
instruction:Maybe you have to wait until the value of the snapshot receives.
So, add async to the function and await to the line of code.