Generate Meteor style _id outside of Meteor

As I understand it, Meteor doesn’t use ObjectIDs in Mongo documents and instead generates a 17(?) character string for the _id. I want to get some plain Node.js stuff working with Meteor and it seems less hassle to use Meteor’s style instead of ObjectIDs (even though I much prefer the ObjectID way… bye bye timestamps)

So is this Meteor _id literally just 17 random [A-Za-z0-9] chars? Is it case sensitive? Is there any format I need to follow?

Take a look at the code for Random.id() as that’s what is used to generate the ids

More specifically: https://github.com/meteor/meteor/blob/556c0e28e94b9351cbf0b28e80a71a4e35f1362a/packages/random/random.js#L155

Awesome, thanks :smile: (and I have just noticed that Random.id() is in the docs but I hadn’t looked in the Packages section right at the end)

Cheers!

No problem! See you tomorrow at the Cardiff Meetup!? :wink:

Yep I will be there!

And in case anyone else has a similar problem, here’s a server-only coffeescript gist to use with plain Node.js applications.

Use at your own risk :fire:

Here is another option, not cryptographically secure but was sufficient for my use case:

const UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz';

function newMeteorId () {
    return [...Array(17).keys()]
    .map(a => 
        UNMISTAKABLE_CHARS[
            Math.floor(Math.random() * UNMISTAKABLE_CHARS.length)
        ]
    )
    .join('')
}
1 Like