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 } 
2
  • 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. Commented Jan 22, 2017 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 Commented Jan 22, 2017 at 14:42

1 Answer 1

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"] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.