Firestore Query - Checking If Username Already Exists

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.

Firestore- checking if username already exists

Hope this will help.

setupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String userName = setupName.getText().toString();

CollectionReference usersRef = firestore.collection("Users");
Query query = usersRef.whereEqualTo("username", userName);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(DocumentSnapshot documentSnapshot : task.getResult()){
String user = documentSnapshot.getString("username");

if(user.equals(userName)){
Log.d(TAG, "User Exists");
Toast.makeText(MainActivity.this, "Username exists", Toast.LENGTH_SHORT).show();
}
}
}

if(task.getResult().size() == 0 ){
Log.d(TAG, "User not Exists");
//You can store new user information here

}
}
});
}
});

Firestore query - checking if username already exists

To solve this, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference allUsersRef = rootRef.collection("all_users");
Query userNameQuery = allUsersRef.whereEqualTo("username", "userNameToCompare");
userNameQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.exists()) {
String userName = document.getString("username");
Log.d(TAG, "username already exists");
} else {
Log.d(TAG, "username does not exists");
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});

In which userNameToCompare is of type String and is the user name of the user with which you want to make the comparison.

Android | Firestore Rules | Check if username & phone already exists

This is a common mistake developers make when using usernames. You gave anyone permission to read your whole database. And even if you manage to put that to only read Users anyone could read all your users data.

I would recommend to remove the first allow read:true and write rules for each path as they should be. Also create a separated collection just for usernames and save all of them there like /usernames/${username} and /phones/${phone}. If the need to be saved together you can do that to.

That way you can very easy check without any query if a username or phone exists by just checking if that path exsists in your database.

You can very easy sync the users collection with those two and even write security rules that prevent creating users in the collection that have a username that already exists in the usernames collection.

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)
}
}

check if username exists in firestore and return true swiftUI

You can use a boolean variable to check if you have found a matching name, and you can set it to true if you find a match.

You can use the following code:

func checkUsername(username: String, completion: @escaping (Bool) -> Void) {

// Get your Firebase collection
let collectionRef = db.collection("users")

// Get all the documents where the field username is equal to the String you pass, loop over all the documents.

collectionRef.whereField("username", isEqualTo: username).getDocuments { (snapshot, err) in
if let err = err {
print("Error getting document: \(err)")
} else if (snapshot?.isEmpty)! {
completion(false)
} else {
for document in (snapshot?.documents)! {
if document.data()["username"] != nil {
completion(true)
}
}
}
}
}

Firestore checking if username exists, best model to not query the whole database?

Actually one of the key characteristics of Firestore is exactly that: the performance of a query is proportional to the size of your result set, not your data set.

So the query performance that you get for finding 1 document in a collection of 5, 24 or 1 million docments will be exactly the same.

In Cloud Firestore, you can use queries to retrieve individual,
specific documents or to retrieve all the documents in a collection
that match your query parameters. Your queries can include multiple,
chained filters and combine filtering and sorting. They're also
indexed by default, so query performance is proportional to the size
of your result set, not your data set
.

So the answer is that you should query your already existing collection of documents and not create smaller collection(s) with a subset of documents for the sake of query performance.

Cloud Firestore: Query to check if a username exists

First of all, there is no need to use addSnapshotListener. This is used only when you want to get realtime updates from the database but it's not your case. You only want to check a username for existens and for that, only a get() call is required.

mQuery.get().addOnCompleteListener(/* ... */)

Second, according to this post, ds!=null && ds.exists() is not required. You only need to check if ds.exists().

And the last thing you need to know is that you can not rely on what value your userNameExistsAlready() method returns. In most cases it will be false and this is because the onEvent() method in your case or onComplete() / onSuccess() in case of using a get() call, are asynchronous. This means that by the time your method returns the result, you haven't finished loading the data from the database. So a quick solve for this would be to use all your logic inside the onEvent() method or if you want to use it outside, I recommend you see the last part of my anwser from this post and also take a look at this video.

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");


Related Topics



Leave a reply



Submit