45

I really like the format of the _ids generated by mongodb. Mostly because I can pull data like the date out of them client side. I'm planning to use another database but still want that type of _id for my document. How can I create these ids without using mongodb?

Thanks!

Community
  • 1
  • 1
fancy
  • 48,619
  • 62
  • 153
  • 231

9 Answers9

57

Use the official MongoDB BSON lib in the client
I have a browser client that generates ObjectIds. I wanted to make sure that I employ the same ObjectId algorithm in the client as the one used in the server. MongoDB has js-bson which can be used to accomplish that.

If you are using javascript with node.

npm install --save bson

Using require statement

var ObjectID = require('bson').ObjectID;

var id  = new ObjectID();
console.log(id.toString());

Using ES6 import statement

import { ObjectID } from 'bson';

const id  = new ObjectID();
console.log(id.toString());

The library also lets you import using good old script tags but I have not tried this.

dipole_moment
  • 5,266
  • 4
  • 39
  • 55
  • 2
    I used id.toHexString() to get the string. – honkskillet Apr 20 '18 at 14:03
  • 2
    This should be the right answer... use the same code MongoDB does folks! I'm using bson 4.0.2 and it's working just fine for me. Note that the name is "ObjectId" (lowercase D) – Robert Aug 28 '19 at 16:53
55

A very easy pseudo ObjectId generator in javascript:

const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
    s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))
Ruben Stolk
  • 12,386
  • 2
  • 18
  • 12
27

Object IDs are usually generated by the client, so any MongoDB driver would have code to generate them.

If you're looking for JavaScript, here's some code from the MongoDB Node.js driver:

https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js

And another, simpler solution:

https://github.com/justaprogrammer/ObjectId.js

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
6

Extending Rubin Stolk's and ChrisV's answer in a more readable syntax (KISS).

function objectId () {
  return hex(Date.now() / 1000) +
    ' '.repeat(16).replace(/./g, () => hex(Math.random() * 16))
}

function hex (value) {
  return Math.floor(value).toString(16)
}

export default objectId
Grant Carthew
  • 177
  • 1
  • 10
4

This is a simple function to generate a new objectId

newObjectId() {
    const timestamp = Math.floor(new Date().getTime() / 1000).toString(16);
    const objectId = timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, () => {
        return Math.floor(Math.random() * 16).toString(16);
    }).toLowerCase();

    return objectId;
}
3

ruben-stolk's answer is great, but deliberately opaque? Very slightly easier to pick apart is:

const ObjectId = (rnd = r16 => Math.floor(r16).toString(16)) =>
    rnd(Date.now()/1000) + ' '.repeat(16).replace(/./g, () => rnd(Math.random()*16));

(actually in slightly fewer characters). Kudos though!

ChrisV
  • 8,748
  • 3
  • 48
  • 38
1

Here's a link! to a library to do that.

https://www.npmjs.com/package/mongo-object-reader You can read and write hexadecimal strings.

const { createObjectID, readObjectID,isValidObjectID }  = require('mongo-object-reader');
//Creates a new immutable `ObjectID` instance based on the current system time.
const ObjectID =  createObjectID() //a valid 24 character `ObjectID` hex string.

//returns boolean
// input - a valid 24 character `ObjectID` hex string.
const isValid = isValidObjectID(ObjectID) 

//returns an object with data
// input - a valid 24 character `ObjectID` hex string.
const objectData  = readObjectID(ObjectID) 

console.log(ObjectID) //ObjectID
console.log(isValid)       // true
console.log(objectData)    /*
{ ObjectID: '5e92d4be2ced3f58d92187f5',
  timeStamp:
   { hex: '5e92d4be',
     value: 1586681022,
     createDate: 1970-01-19T08:44:41.022Z },
  random: { hex: '2ced3f58d9', value: 192958912729 },
  incrementValue: { hex: '2187f5', value: 2197493 } }
*/
RobC
  • 22,977
  • 20
  • 73
  • 80
1

In v5.3.0 its not ObjectID but ObjectId with small capital. import { ObjectId } from 'bson'

Adam
  • 21
  • 1
  • 3
  • Using "ObjectId" is already addressed in the comment section of the original answer provided by @dipole_moment please do not add redundant information as an answer. – varad_s Jun 21 '23 at 13:28
0

There is a detailed specification here

http://www.mongodb.org/display/DOCS/Object+IDs

Which you can use to roll your own id strings

deltanovember
  • 42,611
  • 64
  • 162
  • 244