I would like to generate a short unique alphanumeric value to be used as confirmation codes for online purchases. I've looking into https://github.com/broofa/node-uuid but their uuids are too long and I want to have them be around 8 characters long. What is the best way I can achieve this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
For this purpose I wrote a module that can do that and ever more. Look at its page: id-shorter
10/23/15: See the hashids answer below, as well!
You can borrow from the URL shortener model and do something like this:
Just increment the number to keep it unique:
Note that this is only really useful for "single instance" services that don't mind a certain amount of predictability in the way this is ordered (via basic increment). If you need a truly unique value across a number of application / DB instances, you should really consider a more full featured option per some of the comments.
based on this https://www.npmjs.com/package/randomstring
you can do this
IF each online purchase associated to Unique URL , you can use the backend of simple-short package,which don't require database connection, nor web services :
A little late on this one but it seems like hashids would work pretty well for this scenario.
https://github.com/ivanakimov/hashids.node.js
If you want to target ~ 8 characters you could do, the following that calls for a minimum of 8 chars.
then this:
The accepted answer would be predictable/guessable, this solution should be unique and unpredictable.
Install shortId module (https://www.npmjs.com/package/shortid). By default, shortid generates 7-14 url-friendly characters: A-Z, a-z, 0-9, _- but you can replace - and _ with some other characters if you like. Now you need to somehow stick this shortId to your objects when they're being saved in the database. Best way is to stick them in Schema like this:
I already answered similiar question to myself over here: