如何在Firestore集合中生成并保证唯​​一值? [英] How to generate and guarantee unique values in firestore collection?

查看:40
本文介绍了如何在Firestore集合中生成并保证唯​​一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在Firestore中有一个 order 集合,其中每个订单都需要具有唯一的可读随机订单号,且可以说8位数字:

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'
}

因此,对于每个传入订单,我们都希望生成此唯一编号.在Firestore中,建议采用什么方法来确保没有其他文档在使用它?

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

推荐答案

最简单的保证某个值在集合中唯一的方法是,将该值用作该集合中文档的键/ID.由于按定义,键/ID在它们的集合中是唯一的,因此这暗含了您的要求.

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.

生成唯一ID的唯一内置方法是通过调用 add()方法,该方法将为新文档生成一个UUID.如果您不想使用UUID来识别订单,则必须采用自己的机制.

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.

两种最常见的方法:

  1. 生成一个唯一的号码,并检查该号码是否已被占用.您当然会在事务中执行此操作,以确保没有两个实例可以声明相同的ID.

  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.

保留您发放的最新ID的全局计数器(通常在已知位置的文档中),然后在事务中对其进行增量读取-写入操作以获取任何新ID文档.通常,这是其他数据库对其内置的自动ID字段所做的操作.

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.

这篇关于如何在Firestore集合中生成并保证唯​​一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆