Typically a database can generate a unique ID, most of which is a sequence of numbers, or a combination of sequences like MongoDB, but this form of ID is predictable because it is a sequence. If you want an unpredictable and unique ID, there are methods.
The following is an example of node. JS's environment.
Node-uuid
There is a Node-uuid project on Github that can quickly generate a UUID that conforms to the RFC4122 Specification version 1 or version 4.
Installation can be done either via NPM install Node-uuid or in Package.json. How to use:
var uuid = require ('node-uuid'// generates a V1 (time-based) ID // ' 6c84fb90-12c4-11e1-840d-7b25c5ee775a ' "" // Generate a V4 (random) ID// - ' 110ec58a-a0f2-4ac4-8393-c866d813b8d1 ' "")
It sounds very promising, just ... It's a little too long.
There are some random ways to make a new short string on a UUID basis, but uniqueness becomes a question mark again.
Hashids
Another way, from Hashids, is to generate a hash (hash) string from a number by adding a salt (salted) algorithm. This algorithm is confused to make the results unpredictable, and the uniqueness is still achieved by the number itself, so that (like YouTube) short enough, unpredictable and unique ID.
Installation is similar, but Hashids recommends using a fixed version. Like in the Package.json.
" Dependencies " : { "hashids""0.3.3"}
The method of use is also very simple. Set a string as the salt first.
var Hashids = require ("hashids"), new hashids ("This ismy Salt ");
Then encode the number, which is exactly a numeric array
var hash = hashids.encrypt (12345); // Nkk9 var hash = hashids.encrypt (683941081235); // ABMSWOO2UB3SJ
Array coding can be very interesting to use, for example, in a distributed environment, you can use the machine number + sequence number to combine arrays and then encode.
There's code, there's decoding.
var numbers = Hashids.decrypt ("NkK9"); // [12345]
The encoded output becomes longer as the number increases, and it can specify a minimum length in order to be confused enough.
New Hashids ("This ismy salt"8var hash = Hashids.encrypt (1 ); // gb0nv05e
There are other options, such as controlling the characters used in the output, encoding MongoDB ObjectId, and so on.
The above mentioned two items, each has the advantages and disadvantages, but the purpose is consistent, can be selected according to the actual situation. Two projects have similar implementations in other languages.
How to generate a unique and unpredictable ID