The Cloud Firestore is an awesome platform for quickly prototyping your app ideas into reality, however, it certainly comes with some limitations.
Currently, there is no way for you to enable uniqueness in field values in the whole database. There is a quick workaround, though with queries that you can use.
You want to enforce uniqueness for a field value in your Firestore database for your app.
An app where users have their profiles and a unique username assigned to them.
Natively, the Cloud Firestore provides us with no uniqueness check from either Rules or the SDK. But, of course, there is a workaround.
You can use Firestore queries to get the
document ID which corresponds to the field you want to keep unique. If the query returns
null, that would mean that the database doesn’t contain that value., ergo, the
username, in this case, is available or vice versa.
Of course, you’d like to see some code sample, so let’s get to that.
Consider a sample Users collection with and a few child documents. Our database is set up such that each document corresponds to a single user profile data.
The uId is the doc ID of the document that contains these fields. We have three fields and in a database like this, we generally want to keep the username and email fields unique throughout the database.
To keep things simple, we will simply focus on keeping the username field unique in our database.
This code simply queries the Firebase’s Firestore using the
where() method to get the reference to the document which has the username field occupied with your inputUsername.value. You can then prompt your user to think of some new username since this one is already taken.
So, that’s how you can enforce uniqueness throughout the Firestore database on your app. The same logic can be applied to the email uniqueness issue too. You’ll need to change the query to something like the following depending on what field names you have used:
const query = usersRootRef.where('email', '==', getUserEmailFromInput()).limit(1).get();