Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javascript ObjectId generator
var mongoObjectId = function () {
var timestamp = (new Date().getTime() / 1000 | 0).toString(16);
return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() {
return (Math.random() * 16 | 0).toString(16);
}).toLowerCase();
};
@janbiasi
Copy link

janbiasi commented Aug 3, 2016

Thanks!

@vladimirnani
Copy link

vladimirnani commented Aug 10, 2016

nice!

@dillon-bostwick
Copy link

dillon-bostwick commented Oct 13, 2016

Thanks. Only way I could find to generate in client script

@Thebigbignooby
Copy link

Thebigbignooby commented Feb 23, 2017

thanks, just what I needed for tests 👍

@danielyewright
Copy link

danielyewright commented Mar 8, 2017

Could you use lodash to generate unique ids based on this?

@edwardboyle
Copy link

edwardboyle commented May 6, 2017

Thanks! Nice, came in very handy, web client even.

@zulucoda
Copy link

zulucoda commented Nov 20, 2017

nice 👍

@Jompau
Copy link

Jompau commented Dec 7, 2017

Thank you for this! I implemented this in C# with Unity, here's my version which returns a string:

private string GenerateID ()
{
Int64 val = 0;
var st = new DateTime(1970,1,1);
TimeSpan t = (DateTime.Now.ToUniversalTime () - st);
val = (Int64) (t.TotalMilliseconds+0.5);
char[] startVal = val.ToString ("X").ToCharArray ();
string timestamp = "";
for (int i = 0; i < 10; i++)
{
timestamp += startVal[i];
}
int num = 0;
for (int i = 0; i < 14; i++)
{
num = UnityEngine.Random.Range (1,16);
timestamp += num.ToString ("X");
}
return timestamp.ToLower ();
}

Maybe someone will find it useful :)

@TheBlackDude
Copy link

TheBlackDude commented Jan 31, 2018

Thank You, just what am looking for

@carvakaguru
Copy link

carvakaguru commented Mar 7, 2018

I wrote one for Lua -

function mongoObjectId()
    return string.format("%x", os.time())..string.gsub('xxxxxxxxxxxxxxxx', 'x', function (c)
        return string.format('%x', math.random(0, 15))
    end)
end

@lolpez
Copy link

lolpez commented Apr 4, 2018

OMG thank you so much

@jairovsky
Copy link

jairovsky commented Apr 7, 2018

👌

@md8n
Copy link

md8n commented Apr 22, 2018

And TypeScript - returning the whole oid structure

generateId(): {} {
  const timestamp = (new Date().getTime() / 1000 | 0).toString(16);
  const oid = timestamp + 'xxxxxxxxxxxxxxxx'
    .replace(/[x]/g, _ => (Math.random() * 16 | 0).toString(16))
    .toLowerCase();

  return { "$oid": oid };
}

@ramyhhh
Copy link

ramyhhh commented Sep 24, 2018

The code has a bug, because if random resulted 1 then (Math.random() * 16 | 0).toString(16) will result "10" which is two characters, leading to invalid ObjectId that is supposed to be 24 characters long.

@hieunc229
Copy link

hieunc229 commented Oct 12, 2018

This random string generate function is +50% faster than the method used in the function above (measured by jsben.ch).

function getRandomString(length) {
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var randS = "";

    while(length > 0) {
        randS += chars.charAt(Math.floor(Math.random() * chars.length));
        length--;
    }
    return randS;
}

Ps: generated string will contain uppercase characters, remove upper characters in var chars if you don't want them

@rogeralbinoi
Copy link

rogeralbinoi commented Jan 3, 2019

Thanks! ;)

@GoKooma
Copy link

GoKooma commented Jan 19, 2019

Cool thank you! :) 👍

@skrrp
Copy link

skrrp commented Mar 22, 2019

Thank you so much.

@DanielPopOut
Copy link

DanielPopOut commented Mar 23, 2019

👍 Good job

@ElianCordoba
Copy link

ElianCordoba commented Apr 17, 2019

Thanks!

@loliconer
Copy link

loliconer commented May 29, 2019

The code has a bug, because if random resulted 1 then (Math.random() * 16 | 0).toString(16) will result "10" which is two characters, leading to invalid ObjectId that is supposed to be 24 characters long.

Math.random() returns [0, 1), inclusive of 0, but not 1.

@trylovetom
Copy link

trylovetom commented Mar 5, 2020

@ticdenis
Copy link

ticdenis commented Apr 19, 2020

Based on the above comments I did a sh alias
alias objectidgen='node -e "console.log((function objectidgen(length = 16) {var timestamp = (new Date().getTime() / 1000 | 0).toString(16);return timestamp + \"xxxxxxxxxxxxxxxx\".replace(/[x]/g, _ => (Math.random() * 16 | 0).toString(16)).toLowerCase();})())"'
For macOS users:
alias objectidgen='node -e "console.log((function objectidgen(length = 16) {var timestamp = (new Date().getTime() / 1000 | 0).toString(16);return timestamp + \"xxxxxxxxxxxxxxxx\".replace(/[x]/g, _ => (Math.random() * 16 | 0).toString(16)).toLowerCase();})())" | pbcopy'

@vfa-tamhh
Copy link

vfa-tamhh commented Jun 15, 2020

Thanks! This code useful for me!

@cassiolacerda
Copy link

cassiolacerda commented Jul 18, 2020

Thank you so much man!!!

@stubbyteam
Copy link

stubbyteam commented Jan 6, 2021

Thank you so much man!!!

@killshot13
Copy link

killshot13 commented Jan 9, 2021

I appreciate that you shared this. It is a simple, logical function and integrates nicely with my Express backend.

@prakashsellathurai
Copy link

prakashsellathurai commented Jul 8, 2021

@solenoid what about the collision of this random id generation method?

@thauealfredo
Copy link

thauealfredo commented Aug 26, 2021

Perfect, thanks!!

@BathriNathan
Copy link

BathriNathan commented Oct 29, 2021

simple and quick solution. thanks

here is the function in coffee script:
mongoObjectId: () ->
timestamp = ((new Date).getTime() / 1000 | 0).toString(16)
timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, ->
(Math.random() * 16 | 0).toString 16
).toLowerCase()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment