How to generate and guarantee unique values in firestore collection?

 ̄綄美尐妖づ 提交于 2021-01-29 14:28:51

问题


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 (?).


回答1:


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.



来源:https://stackoverflow.com/questions/58213316/how-to-generate-and-guarantee-unique-values-in-firestore-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!