Ad

How To Call A Function When Firebase Query Doesn't Match Anything In The Database

I'm trying to implement a friend adding system for a react native project. I'm using firebase realtime database. The problem is when I use the 'equalTo()' function for querying, if there is no matching data in the database I don't get a result and I can't call a function to say that there are no users with this username. All I want to do is to be able to say that there were no users found with that username.

I use 'child_added' event type to get the userID of the user that matches the searched username but if there is no matching username my callback function never gets called. If I use 'value' event type then snapshot.key returns the string 'users' and snapshot.val() doesn't have the userID of the matching user (if there is one).

This is the current database:

"users": {
    "uid1": {
        "user_details": {
            "username": "username1"
       }
    },
    "uid2": {
        "user_details": {
            "username": "username2"
       }
    }
}

This is the code:

firebase.database().ref('users')
    .orderByChild('user_details/username')
    .equalTo(username)
    .once('child_added', snapshot => {
        console.log('User found');
    })
    .then(() => {
        console.log('No users found')
    });

username is passed with a function call.

If the query can't find a result that is equal to the username once() is never executed or at least its second argument is never executed and then() is never executed as well.

I don't get any errors.

Ad

Answer

The child_added event is fired for each child node that matches the query. If there are not child nodes matching the query, child_added isn't fired.

To detect the absence of any matches, you'll need to listen to the value event:

firebase.database().ref('users')
    .orderByChild('user_details/username')
    .equalTo(username)
    .once('value', snapshot => {
      if (!snapshot.exists()) {
        console.log('No users found')
      };
    });

In this case, you might as well add the positive detection to the value listener too, with:

firebase.database().ref('users')
    .orderByChild('user_details/username')
    .equalTo(username)
    .once('value', snapshot => {
      if (!snapshot.exists()) {
        console.log('No users found')
      }
      else {
        snapshot.forEach(child => {
          console.log('User found: '+child.key)
        });
      }
    });
Ad
source: stackoverflow.com
Ad