[英]Generate Unique Short Number instead of using Doc ID's?
I have a business case where I need to have documents in a collection containing a number field that will be unique than another document's number field.我有一个商业案例,我需要在一个集合中包含一个包含数字字段的文档,该数字字段将比另一个文档的数字字段唯一。 This number has to be short to type and should be random.
这个数字必须是简短的类型,并且应该是随机的。 For example: 2832. Now I know this doesn't scale since there can only be 10k possible number combinations for a 4-digit number, however, that's fine at the moment.
例如:2832。现在我知道这无法扩展,因为 4 位数字只能有 10k 个可能的数字组合,但是,目前这很好。
I wanted to know the best way to implement this in Firebase.我想知道在 Firebase 中实现这一点的最佳方法。 I was thinking of creating a 4-digit random number in JavaScript then whenever a new number is generated, do a check on a separate collection that contains one document with an array field that will contain every unique number.
我正在考虑在 JavaScript 中创建一个 4 位随机数,然后每当生成一个新数字时,对包含一个包含每个唯一数字的数组字段的文档的单独集合进行检查。 If that number already exists, generate a new number and check again, if it doesn't exist, then add that unique number to the array.
如果该号码已经存在,则生成一个新号码并再次检查,如果不存在,则将该唯一号码添加到数组中。
Is this the optimal approach?这是最佳方法吗? Thanks.
谢谢。
Whether something is optimal is hard to say, but the approach sounds like a reasonable starting point.很难说某件事是否是最优的,但这种方法听起来是一个合理的起点。
I'd probably have started with having a separate document with the number as its document ID, but for 10K values that might not even be needed - which means your approach will be simpler.我可能已经开始有一个单独的文档,其编号作为其文档 ID,但对于 10K 的值,甚至可能不需要 - 这意味着您的方法会更简单。
Be sure to use a transaction to perform updates to the document, anduse security rules to ensure no client can write a value that's already in the array.确保使用事务对文档执行更新,并使用安全规则确保没有客户端可以写入数组中已经存在的值。
Well, since you are already open to maintaining an array of used numbers, ou could eliminate the "retry" factor by using the full pre-randomized array and a "pointer" which is a simple number from 0-9999.好吧,既然您已经愿意维护一个使用过的数字数组,您可以通过使用完整的预随机数组和一个从 0-9999 的简单数字“指针”来消除“重试”因素。
Firestore does manage data contention: https://firebase.google.com/docs/firestore/transaction-data-contention Firestore 确实管理数据争用: https://firebase.google.com/docs/firestore/transaction-data-contention
So getting the current pointer value and incrementing it in a transaction would make it so the pointer value is used once only and allow you to get a guaranteed unique value from your pre-randomized array at that pointer value position.因此,获取当前指针值并在事务中将其递增将使指针值仅使用一次,并允许您从该指针值 position 的预随机数组中获得有保证的唯一值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.