Search code examples
angularfirebasegoogle-cloud-datastoregoogle-cloud-firestoreangularfire2

Check a document field for a specific value in Cloud Firestore


I want to create a user registration with custom usernames. I store the user's username on a user document in Firestore. How can I validate a username already exists in my Users Collection?

Maybe someone already have snippet for reactive form validation?


Solution

  • There is no efficient way to check all documents in a collection for a specific value. You would have to read each document in turn, and check them. That is prohibitive both from a performance and a cost standpoint.

    What you can instead do is create an additional collection (typically called a reverse index, or reverse map) where you use the username as the name of the document, and (for example) the user's UID as the data of the document. You can then easily check if a username is already taken by checking for the existence of a document with that specific name, which is a direct access lookup and thus highly scaleable.

    Since you tagged with google-cloud-datastore; if you are indeed looking for an answer for that database too, check Unique email in Google Datastore.