Check uniqueness of randomly generated IDs

so, I am working on an e com project, where I need to assign customer id to every new customer. I am using a random number and string generator function to generate a 6 digit customer id (First 3 digits are a string amd last 4 are a number, like QAS2360) and then saving it to mongodb along with the customer details. To make the whole system fail safe, I want to check if the customer id randomly generated by my existing function against a ll the existing customer ids in the DB. and in case, if there is a match, I want to generate another customer id and if there’s no match, I want to pass it to the mongodb models and save it to db with customer’s details.

I am thinking to construct a function and use loops inside it, But I am not sure how to do ir?

First of all, 3 letters and 4 digits will compose a 7-character ID :slight_smile:
It seems pretty unique to me, personally. Odds of the same ID are quite slim in such construct: 26 x 26 x 26 x 10 x 10 x 10 x 10 ~ 1 / 175 000 000, which until the first couple millions of users seems impossible to hit )) But, it’s definitely not scalable at all and two options to fix scalability:

  1. Use IDs provided by MongoDB, which are more or less universally unique
  2. Use external library, like uuid to generate one yourself

Definitely don’t do this :point_down:


Thanks for the reply mate. Is there a way to create ids using uuid generators with my set of rules like 3 letters and 4 digits?

Two other approaches (that somewhat mess the security, but in general OK):

  1. Incremental index: Start with AAA0001 and keep incrementing until ZZZ9999, after that you can always switch to 8-character IDs
  2. Involve date to a certain precision and combine with incremental index: client # 1 during this particular minute. Also scalable to changing precision.

No, I don’t think so.

1 Like

If it’s really important that customers have some ID that is in some specific human readable format like you want, then use UUIDs for each user and use those internally, and also generate one of those human readable IDs for them. The user never needs to see the UUID, the system never has to depend on possibly non-unique human-readable IDs. Does mean that if a user uses their ID to (for example) log in, then they can’t just use that, it has to be in combination with something else so that you can ensure it doesn’t try to log the wrong user in.

1 Like