2

Lets say we have a order collection in firestore where each order needs to have a unique readable random order number with lets say 8 digits:

{
    orderNumber: '19456734'
}

So for every incoming order we want to generate this unique number. What is the recommended approach in firestore to make sure no other document is using it?

Note: One solution would be querying existing docs before saving, but this is not working in a concurrent scenario where multiple orders arrive at the same time (?).

fischermatte
  • 3,327
  • 4
  • 42
  • 52

1 Answers1

5

The easiest to guarantee that some value is unique in a collection, is to use that value as the key/ID for the documents in that collection. Since keys/IDs are by definition unique in their collection, this implicitly enforces your requirement.

The only built-in way to generate unique IDs is by calling the add() method, which generates a UUID for the new document. If you don't want to use UUIDs to identify your orders, you'll have to roll your own mechanism.

The two most common approaches:

  1. Generate a unique number and check if it's already taken. You'd do this in a transaction of course, to ensure no two instances can claim the same ID.

  2. Keep a global counter (typically in a document at a well-known location) of the latest ID you've handed out, and then read-increment-write that in a transaction to get the ID for any new document. This is typically what other databases do for their built-in auto-ID fields.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 5
    It may be interesting to note that using the `add()` method will not incur any cost, while checking if a number already exists or keeping a global counter involve a document read, which has a (small) cost. – Renaud Tarnec Oct 03 '19 at 07:10