winston
winston

Reputation: 3100

Firebase query can't find email address?

I'm have a key in my Firebase database called "users" which contain keys for email and name. I'm trying to create a simple query that will find a user based on email address, but the query is not returning any results.

let rootRef = FIRDatabase.database().reference()
let email = emailTextField.text

rootRef.child("users").queryEqualToValue(email, childKey: "users").observeEventType(.Value, withBlock: { snapshot in
        if snapshot.exists() {
            print("user exists")

        } else if !snapshot.exists(){
            print("user doesn't exist")

        }
    })

My console always prints "user doesn't exist" even if the email text field is identical to what is shown in my database.

Any ideas as to what's wrong?

Thanks!!

Upvotes: 0

Views: 796

Answers (1)

Jay
Jay

Reputation: 35658

Try this:

let usersRef = self.rootRef.childByAppendingPath("users")
let email = emailTextField.text

usersRef.queryOrderedByChild("email").queryEqualToValue(email)
                .observeEventType(.Value, withBlock: { snapshot in
     if snapshot.exists() {
          print("user exists")

     } else {
          print("user doesn't exist")

     }
})

You need to be careful though... .Value will return all nodes that have an email address equal to the one you are looking for. In general that would be one, however, if there are 5, .Value will contain all 5 so it would be safer to iterate over the snapshot.

for child in snapshot.children {
   let email = child.value["whatever key:value you want"] as! String
}

Upvotes: 2

Related Questions