I'm writing a Node API and got a model for which I gotta generate a random number of 15 digits. This must be unique and should not look trivial (I can't get an autoincrement).
I really don't want to generate a number and query against Mongo database for existance checking. I would have to generate some kind of while loop based on promises that way.
I thought about simply using new Date().epoch
but, is this going to be unique? could I ever get a duplicate?
Then I also thought on appending something like:
function privateKey (howMany, chars) {
chars = chars
|| "0123456789";
var rnd = crypto.randomBytes(howMany)
, value = new Array(howMany)
, len = chars.length;
for (var i = 0; i < howMany; i++) {
value[i] = chars[rnd[i] % len]
};
return parseInt(value.join(''));
}
To include a duplicity avoiding. How should I implement this?
I know there's uuid and Mongo ObjectId but they're not only numbers.
I don't think it's a good idea. One of the reasons is system time skew. Upon synchronizing time with some benchmark server you would get duplicates. In fact this can happen on the runtime every couple of hours. Some servers have serious time drift and they sync time every one in a while. Any time this happens you can get duplicates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With