Before creating a new user I want to check if creating username property already exists in Firebase Database.
Checking function is:
let databaseRef = Database.database().reference()
databaseRef.child("users").queryOrdered(byChild: "username").queryEqual(toValue: loginRegisterTextField.text).observeSingleEvent(of: .value, with: { (snapshot: DataSnapshot) in
if snapshot.exists() {
print("Login exists")
} else {
print("Login does not exist")
}
})
JSON is:
Rules are for node users:
{
"rules": {
"users" : {
".read": "auth != null",
"$uid" : {
".write": "auth != null && auth.uid == $uid",
}
},
Is it possible to write a rules to check existing of username without a new uid?

usernamechild node you're using has nothing to do with a UID, and in fact, doesn't have anything to do with rules either. The problem with this code flow is that, in order to check to see if a username exists, the user must be authenticated, but if this is a new user, they are not yet authenticated, so that won't work. One option is to create the firebase account first (which authenticates the user) then ask them to create a username. In that scenario, your code will work pretty much as is. Otherwise you can keep a publicly accessible username list, or leverage cloud functions.