skip to Main Content

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


  1. Firebase Realtime Database queries consist of multiple parts:

    1. An instruction to order the child nodes of a path on a specific part of the content.
    2. One or more instructions to filter the nodes based on that value.
    3. An optional instruction to limit the number of results.

    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:

    const queryRef = query(
      codesRef, 
      orderByValue(), // 👈
      equalTo('-NZEG-Ie9TKAdBmqw3Oc')
    );
    
    Login or Signup to reply.
  2. 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.

    get(queryRef)
      .then((snapshot) => async {
       val val = await snapshot.val();
        console.log(val);result
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search