Querying for existing nodes in Firebase is returning null

My tree structure looks like in FireBase

  • BOOKS
  • USERS
    • UserA_ID
    • UserB_ID
    • UserC_ID
      • UserName:@””
      • UserEmail:@””
      • UserBookReadCount:@””

Before I go and update the ‘BookReadCount’, I try to query for the existence of this user using the following code. In the

  • ios: How do I add a new UDID to provisioning profile without a tethered device?
  • UITableView Scroll event
  • Upload NSURLSesssion becomes invalidated in sharing extension in ios8 with error NSURLErrorDomain Code=-995
  • Designing the iPhone interface in a nib or in code?
  • HTTP “Content-Disposition: attachment” and downloading files on iOS web browser
  • iPhone/iPad browser simulator?
  • FQuery* query = [[userRef queryOrderedByKey] queryEqualToValue:userIDKey];
    [query observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot)
                {
                    NSLog(@"Snapshot value: %@", snapshot.value);
                    if(snapshot.hasChildren)
                    {
                       // UserX_ID exists. Use 'updateChildValues' to update the data
                    }
                    else
                    {
                       // UserX_ID does NOT exist. Use 'setValue' to create the data
                    }
    
                }];
    

    If the user does not exist I then use ‘setValue’ to add a new user to this list. If the user exists then I use ‘updateChildValues’ to update the users data. All this is working fine.

    The problem I’m facing is with the queries. Even if the user exists or doesn’t exist, the above query always returns null.

    Any thoughts on something obvious that I’m missing ?

    Solutions Collect From Internet About “Querying for existing nodes in Firebase is returning null”

    A couple of things. To test for null you should really

     if (snapshot.value == [NSNull null])
    

    Here’s a slightly modified implementation of your code that includes the NSNull check.

    Firebase *ref = [self.myRootRef childByAppendingPath:@"users"];
    
    FQuery *query = [[ref queryOrderedByKey] queryEqualToValue:@"UserC_ID"];
    
        [query observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
    
            if (snapshot.value == [NSNull null]) {
                NSLog(@"was null");
            } else {
                NSLog(@"key: %@    %@", snapshot.key, snapshot.value);
            }
        }];
    

    I set up a test Firebase with the same structure you are using and it works correctly; returns null for nonexistent user id’s and returns the node UserC_ID when it does.

    So maybe your code that sets the userIDKey is misbehaving or perhaps your userRef is wonky.