0

I have a Firebase table called Users where I store user objects of form

"users": {
   "user1": {
      "name": "username",
      "id": "userID",
    },
}

How can I create a proper query to get all users with 'name'.

I tried this, but this returns a null snapshot:

let ref = self.getDatabaseInstanceWith(child: FirebaseIdentifiers.tableUsers)
   ref.queryOrdered(byChild: "name")
      .queryEqual(toValue: "username")
      .observe(.value, with: { snapshot in
}
AL.
  • 36,815
  • 10
  • 142
  • 281
anho
  • 1,705
  • 2
  • 20
  • 38
  • What is `FirebaseIdentifiers.UserUUID`? Because without seeing that I have a feeling that you're trying to compare the user's name to their UID. – Frank van Puffelen Jan 22 '17 at 14:41
  • this would be the ''name'' from the user1 (or at least would want it to be).... will update the question... I wrote the wrong identifier – anho Jan 22 '17 at 14:42

1 Answers1

1

A Firebase query to retrieve the uid's for users named John

let queryRef = usersRef.queryOrdered(byChild: "name").queryEqual(toValue: "John")

//get all of the comments tied to this post
queryRef.observeSingleEvent(of: .value, with: { snapshot in

     for snap in snapshot.children {
          let userSnap = snap as! FIRDataSnapshot
          let userDict = userSnap as! [String:AnyObject]
          let uid = userSnap.key                
          let name = userDict["name"] as! String

          print("key = \(uid)") //prints the johns uids
     }
})

However....

The above code requires a slightly different Firebase Structure.

A typical Firebase design pattern is to use the uid of the user as the key to the user node

users
   uid
    name: "some name"
    location: "somewhere"

If you want to use your structure, then the id would just be retrieved as a child node instead of the userSnap.key

   let name = userDict["name"]
   let uid = userDict["id"]
Jay
  • 34,438
  • 18
  • 52
  • 81