Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs generate short unique alphanumeric

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?

like image 279
teggy Avatar asked Jun 11 '12 18:06

teggy


3 Answers

10/23/15: See the hashids answer below, as well!

You can borrow from the URL shortener model and do something like this:

(100000000000).toString(36);
// produces 19xtf1ts

(200000000000).toString(36);
// produces 2jvmu3nk

Just increment the number to keep it unique:

function(uniqueIndex) {
    return uniqueIndex.toString(36);
}

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.

like image 93
Wes Johnson Avatar answered Oct 15 '22 19:10

Wes Johnson


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

hashids (Hash ID's) creates short, unique, decryptable hashes from unsigned integers

var Hashids = require('hashids'),
hashids = new Hashids('this is my salt');

var hash = hashids.encrypt(12345);
// hash is now 'ryBo'

var numbers = hashids.decrypt('ryBo');
// numbers is now [ 12345 ]

If you want to target ~ 8 characters you could do, the following that calls for a minimum of 8 chars.

hashids = new Hashids("this is my salt", 8);

then this:

hash = hashids.encrypt(1);
// hash is now 'b9iLXiAa'

The accepted answer would be predictable/guessable, this solution should be unique and unpredictable.

like image 36
James Moore Avatar answered Oct 15 '22 19:10

James Moore


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:

var shortId = require('shortid');
var PurchaseConfirmationSchema = mongoose.Schema({
  /* _id will be added automatically by mongoose */
  shortId: {type: String, unique: true, default: shortId.generate}, /* WE SHOULD ADD THIS */
  name: {type: String},
  address: {type: String}
});

I already answered similiar question to myself over here:

Shorten ObjectId in node.js and mongoose

like image 1
Drag0 Avatar answered Oct 15 '22 19:10

Drag0