如何为Firestore中的文档制作自定义自动生成的ID [英] how can I make custom auto generated IDs for documents in firestore

查看:39
本文介绍了如何为Firestore中的文档制作自定义自动生成的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的项目,我需要可以轻松共享的ID,因此firestores默认自动生成的ID无法使用.
我正在寻找一种自动生成ID的方法,例如 8329423 ,该ID可以在0到9999999的范围内递增或随机选择.

For my project I need ids that can be easily shared, so firestores default auto generated ids won't work.
I am looking for a way to auto generate id like 8329423 that would be incremented or randomly chosen in range 0 to 9999999.

推荐答案

Firestore的自动ID字段旨在统计地确保没有两个客户端会生成相同的值.这就是为什么它们要长久的原因:它是为了确保它们中有足够的随机性(熵).

Firestore's auto-ID fields are designed to statistically guarantee that no two clients will ever generate the same value. This is why they're as long as they are: it's to ensure there is enough randomness (entropy) in them.

这使Firestore可以完全在客户端确定这些密钥,而无需在服务器上查找其生成的密钥之前是否已在其他客户端上生成.而这又具有以下主要优点:

This allows Firestore to determine these keys completely client-side without needing to look up on the server whether the key it generated was already generated on another client before. And this in turn has these main benefits:

  1. 由于密钥是在客户端生成的,因此即使客户端未连接到任何服务器,也可以生成密钥.
  2. 由于密钥是在客户端生成的,因此无需往返服务器即可生成新密钥.这样可以大大加快这一过程.
  3. 由于密钥是在客户端生成的,因此在生成密钥的客户端之间没有争用.每个客户端仅根据需要生成密钥.

如果这些好处对您的用例很重要,那么您应该强烈考虑是否要创建比Firestore更好的唯一ID.例如,Firestore的ID具有62 ^ 20个唯一值,这就是为什么从统计学上保证它们在很长一段时间内永远不会生成相同值的原因.您建议的0-9999999范围具有1百万个唯一值,这很可能会产生重复值.

If these benefits are important to your use-case, then you should strongly consider whether you're likely to create a better unique ID than Firestore already does. For example, Firestore's IDs have 62^20 unique values, which is why they're statistically guaranteed to never generate the same value over a very long period of time. Your proposed range of 0 - 9999999 has 1 million unique values, which is much more likely to generate duplicate.

如果您真的想要这种ID方案,则需要将已经给出的ID存储在服务器上(可能在Firestore中),以便在生成新密钥时可以对其进行检查.执行此操作的一种非常常见的方法是保留您已在文档中分发的最后一个ID的计数器.要生成新的唯一ID,您:

If you really want this scheme for IDs, you will need to store the IDs that you've already given out on the server (likely in Firestore), so that you can check against it when generating a new key. A very common way to do this is to keep a counter of the last ID you've already handed out in a document. To generate a new unique ID, you:

  1. 从文档中读取最新的计数器值.
  2. 增加计数器.
  3. 将更新的计数器值写入文档中.
  4. 在代码中使用更新的计数器值.

由于此读写更新来自多个客户端,因此您将需要使用一个事务.还请注意,客户端现在正在协调密钥生成,因此您将遇到可生成密钥数量的吞吐量限制.

Since this read-update-write happens from multiple clients, you will need to use a transaction for it. Also note that the clients now are coordinating the key-generation, so you're going to experience throughput limits on the number of keys you can generate.

这篇关于如何为Firestore中的文档制作自定义自动生成的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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