anho
anho

Reputation: 1735

Firebase query of table

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
}

Upvotes: 0

Views: 218

Answers (1)

Jay
Jay

Reputation: 35667

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"]

Upvotes: 1

Related Questions