Skip to content

Instantly share code, notes, and snippets.

@greenlikeorange
Created October 16, 2014 05:43
Show Gist options
  • Save greenlikeorange/fcc9993db51edd10bffa to your computer and use it in GitHub Desktop.
Save greenlikeorange/fcc9993db51edd10bffa to your computer and use it in GitHub Desktop.
Short and Secure MongoDB ObjectID
var asciiStr = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 + /".split(" ");
var my64shortStr = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 - _".split(" ");
var ascii2my64 = {};
var my64toascii = {};
for(var i = 0; i < asciiStr.length; i++){
ascii2my64[asciiStr[i]] = my64shortStr[i];
my64toascii[my64shortStr[i]] = asciiStr[i];
}
// Encode
function to64(id){
id = new Buffer(id, 'hex').toString('base64');
for(var k in ascii2my64){
id = id.replace(k,ascii2my64[k],'g');
}
return id;
}
// Decode
function from64(str){
for(var k in my64toascii){
str = str.replace(k,my64toascii[k],'g');
}
return new Buffer(str, 'base64').toString('hex');
}
// Test
var objid = '543f560dcb65dec05d01995a';
var shortedid;
console.log(shortedid = to64(objid)); // VD9WDctl3sBdAZla
console.log(from64(shortedid) === objid); // true
// Usage and Example
// Implement to Schema and Model
var mongoose = required('mongoose');
var bookSchema = new Schema({
title: { type: String, trim: true, required: true },
author: { type: String, trim: true, required: true },
published: { type: Date, required: true },
price: { type: Number, required: true }
});
var book = mongoose.model('book', bookSchema);
// To get shortedId from single object
bookSchema.virtual('shortedID').get = function(){
return to64(this._id);
}
// Find with ShortedId from Model
book.findByShortedId = function(id, fields, options, callback){
return this.findById(from64(id, fields, options, callback));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment