0

After using snapshot.exists(), username will always return as available upon signup. How can I alter my code to properly check whether or not a username has already been taken?

Here is a snippet of the json under "users" in the database:

{
  "UserID#" : {
  "credentials" : {
  "name" : "testuser",
  },
 }
}  

My code currently looks like:

let usersDB = Database.database().reference()
var taken = false
  usersDB.child("users").child("credentials").queryOrdered(byChild:"name").queryEqual(toValue: username.lowercased()).observeSingleEvent(of: .value, with: { (snapshot) in

        if snapshot.exists() {
            taken = true
            print("Username is not available.")
            usernameAlert()
        } else { 
          print("User is available")
        }

No matter if the username is already taken on the database, the snapshot will say it does not exist.

Solutions I've tried with no success: check if the username exist in Firebase Query users in Firebase to check if username exists during sign up process Firebase querying for unique Username swift Check if user exists with username using Swift and Firebase Swift & Firebase | Checking if a user exists with a username

grosa
  • 5
  • 4
  • Please edit your question to include a snippet of the JSON under `users/credentials` (as text, no screenshots please). You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen May 17 '19 at 23:43
  • Updated question to include JSON snippet – grosa May 18 '19 at 00:05

1 Answers1

1

You're now checking under each child node of /users/credentials for a property named name. What you instead want is to check each child node of /users for a property at credentials/name, which you do with:

usersDB.child("users").queryOrdered(byChild:"credentials/name").queryEqual(toValue: ...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807