Check If the Username Exist in Firebase

How to search if a username exist in the given firebase database?

EDIT: New answer, old one still below.

I would get rid of your method "checkFirebaseForUsername" because it will always return 0, no matter what.

What you need to do is this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
// Let the user know he needs to pick another username.
} else {
// User does not exist. NOW call createUserWithEmailAndPassword
mAuth.createUserWithPassword(...);
// Your previous code here.

}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

Old Answer:

{
users:
{
apple[X]:
{
username : apple[Y]
email : apple@xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango@xy.com
uid : erererer
}
}
}

If for example, the node apple[X] will always have the same name as the child property "username":apple[Y], then it is as simple as this.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
} else {
// "username" does not exist yet.
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

however, if say, the node apple[X] can have a different value than the property apple[Y], and you want to see if any node exists where the "username" property is the same, then you will need to do a query.

 Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo("usernameToCheckIfExists");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
// 1 or more users exist which have the username property "usernameToCheckIfExists"
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

How to check if username already exists in firebase Realtime Database

The query is expecting userName to be a direct field in username node and because userId is not same for everyone you cannot specify a neste path. If you remove the username node and restructure the DB as shown below, the same query should work perfectly:

Users
| // remove [username] node from here
|-userId // userId from Firebase Auth
|
|-userName
|-otherFields

If you want to retain existing structure then you can just check if a node with given username exists:

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child("userName");

Firebase Checking if username exists

This:

userNameRef.orderByChild("username").equalTo(currentUsername)

is a query it is like saying where username= currentUsername

The currentUsername is the logged in user, the datasnapshot is users.

So in your database you have:

users
userid
username: currentUsername

When you use if(dataSnapshot.exists()){ it checks the snapshot which is users and checks the where condition, if theys exists in the database then it will enter the if clause.

If the where condition does not exists in the database then it will enter the else.

check if the username exist in Firebase

The easiest way of achieving this is when registering a user, create the user with their unique UID and save all their data inside there like you're doing BUT also create a node called "usernames" that simply holds all the usernames that are signed up with the key as their username and the value as 1 like so:

Usernames {
- username: 1
}

When a user signs up and then goes to enter a username, you can check if it exists like so:

let username = "username that user has typed in"

let reference = Database.database().reference()
reference.child("usernames").observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.hasChild(username) {

print("Already exists")

} else {

print("Doesn't exist")

}

}, withCancel: nil)

EDIT:

Thanks to @FrankvanPuffelen, here's a much more efficient way of doing this - without looping through every single username.

let reference = Database.database().reference()
reference.child("usernames").child(username).observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.exists() {

print("Username already exists")

} else {

print("Username doesn't already exist")

}

}, withCancel: nil)

javascript - Firestore checking if username already exists

To be straight forward you can just try this code:

const username = ""
const userNameDoc = await firebase.firestore().collection("users").where("username", "==", username).get()
if(!userNameDoc.empty) {
console.log("This username is already taken!");
}

But as this is all frontend so this can be bypassed if anyone wants to. All this requires you to give all users access to the whole users collection which won't be ideal. So you should ideally use a cloud function or you own server environment for better security.

For example, you can block all direct requests to Firestore collection using security rules and create users using the Admin SDK in cloud functions.

You can use the code below in your cloud function to create a new user by checking if the username is still valid.


exports.createNewUser = functions.https.onCall(async (data, context) => {
const userEmail = data.email
const userName = data.name
const userPass = data.password
const userNameDoc = await admin.firestore().collection("users").where("username", "==", username).get()
if(!userNameDoc.empty) {
console.log("This username is already taken!");
return {result: "Username is already taken!"}
}
return admin
.auth()
.createUser({
email: 'user@example.com',
password: userPassword,
displayName: userName,
})
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
console.log('Successfully created new user:', userRecord.uid);
return {result: "User Created!"}
})
.catch((error) => {
console.log('Error creating new user:', error);
return {result: error}
});
});

The 2nd method is way more secure than first one for your Firestore DB.

Check if username exists in firebase database in javascript

To check if username exists:

firebase.database().ref().child("users").orderByChild("username").equalTo(username_here).on("value", function(snapshot) {
if (snapshot.exists()) {
console.log("exists");
}else{
console.log("doesn't exist");
}
});

more info here:

https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists

Checking if username already exists gives error kotlin


I translated the code below from java

That's not the correct way of "translating" that code from Java to Kotlin, since that answer provides a solution for getting data only once. So to be able to do that in Kolin programming language please use the following lines of code:

val rootRef = FirebaseFirestore.getInstance()
val allUsersRef = rootRef.collection("all_users")
val userNameQuery = allUsersRef.whereEqualTo("username", "userNameToCompare")
userNameQuery.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result) {
if (document.exists()) {
Log.d("TAG", "username already exists")
val userName = document.getString("username")
//Do what you need to do with the userName
} else {
Log.d("TAG", "username does not exists")
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.exception)
}
}


Related Topics



Leave a reply



Submit