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.
I wanted to know the best way to implement this in 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. 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.
2
Answers
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.
Be sure to use a transaction to perform updates to the document, and use 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.
Firestore does manage data contention : 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.