title: How to check if email already exists in Firestore db
body: <p>I have implemented Auth method for the <strong>Firestore</strong> database, but when the user tries to register with the same email, the app crash. I'd like to implement a function to check if the email already exists (if it does, fire UIAlert, otherwise if it doesn't, create a new user).</p>
  
  <p>I have so far: </p>
  
  <pre><code>Auth.auth().createUser(withEmail: email, password: password) { (Result, err) in
  
  let db = Firestore.firestore()
              let docRef = db.collection("email users").document("email")
              docRef.getDocument { (document, error) in
                  if let document = document, document.exists {
  
                      let emailAlreadyInUseAlert = UIAlertController(title: "Error", message: "Email already registered", preferredStyle: .alert)
                      emailAlreadyInUseAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                      self.present(emailAlreadyInUseAlert, animated: true, completion: nil)
  
                      return
                  } else {
                      let db = Firestore.firestore()
                      db.collection("email users").addDocument(data: [
                                                      "firstName": firstName,
                                                      "lastName": lastName,
                                                      "email": email,
                                                      "created": Timestamp(date: Date()),
                                                      "uid": Result!.user.uid
                                                  ])
  
                              }
                              self.transitionToHome()
  
                      }
  
  
                      }
                  }
              }
  
  
  func transitionToHome() {
  
      let homeViewController = storyboard?.instantiateViewController(identifier: "HomeViewController") as? HomeViewController
  
      view.window?.rootViewController = homeViewController
      view.window?.makeKeyAndVisible()
  
     }
  }
  </code></pre>
  
  <ul>
  <li>At this code the UIAlert doesn't fire, and have an error at : <strong>"uid": Result!.user.uid  - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value</strong>. When creating new user with unique email, it works as it should, the user is created.</li>
  <li>If I change <strong>if let document = document, document.exists</strong> to <strong>if error !=nil</strong>, I get the UIAlert when the email already exist and also if it doesnt exist, the code of creating user doesnt execute.</li>
  <li>Even tried to implement addsnapshotlistener, no luck.</li>
  </ul>
  
  <p>Any suggestions? Thank you</p>