Skip to content
Advertisement

How to find a user from firebase by username?

so I wrote a method to look through all the users in my firebase firestore database in react native and it looks like this:

usernameTaken: async (name) => {
        await db.collection("users").get().then(querySnapshot => {
            querySnapshot.forEach(documentSnapshot => {
                if (documentSnapshot.data().username === name) {
                    return true;
                }
            });
        });
        return false;
    }

My data is listed by the user id, and one of the direct document fields is username. As you may tell, looking through every single one of the documents to find a matching username is very inefficient, and I was wondering if there was a way to make this a lot more efficient? The goal is to block and matching usernames so in my app people don’t have the same usernames. Any help would be largely appreciated, Thank you!

Advertisement

Answer

The best way to do this would be to make the user_id the name of your container inside “users” like so and use this name as the unique identifier for anything related to said user. ”’

|- users
|-- unique_janedoe
|--- address
|--- email 
|-- unique_johndoe
|--- address
|--- email

”’ Your other option would be to make a separate folder containing a list of all usernames, populated each time a user is added to the database.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement