Emulating Unique Constraints in Google Firestore
Compared to most popular databases, Google Firestore is very minimalistic.
A very important feature that it lacks, is that of unique constraints (unique indexes). This feature is particularly important when we are building a system that allows users to pick a username
. If we don’t enforce uniqueness we could end with two users with the same username
, which is not what we want.
Using Document ID and transactions
If we are able to use the username
as the user id, then things are a little easier. We can follow these steps to create a new user (wrapped in a transaction):
- Get user by ID (username)
- If it exists, user is taken, return an error
- If it doesn’t exist, add it
Before we proceed with this solution, there are a few things that are important to know about transactions in firestore: