Mike
Mike

Reputation: 1336

Creating Meteor-friendly id's in Mongo?

In meteor, when I create an item in a collection, the generated id for the item usually looks like:

"_id" : "vxqbpic8yLdc6Ehor"

However, when I insert a row directly in Mongo, it's generated id looks like:

"_id" : ObjectId("549af35926cee46520611838")

Is there a way for me to insert data directly into mongo generating an id similar to the way meteor does, or is that something special with meteor? I'd be happy with just dropping the "ObjectId()" wrap around the value, if that's possible.

Upvotes: 1

Views: 1032

Answers (2)

Chris Magnuson
Chris Magnuson

Reputation: 5949

Here is a function that uses Math.random() to generate Meteor Id's:

const UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz';

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

My understanding is that the ids generated using Meteor's random.js are more truly random where as this is not but I believe for most use cases this will be sufficiently random.

Upvotes: 0

Serkan Durusoy
Serkan Durusoy

Reputation: 5472

What meteor actually does is create a random 17 character string that consists of characters from within 23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz

https://github.com/meteor/meteor/blob/devel/packages/random/random.js is what does that. Namely the RandomGenerator.prototype.id(17) function.

So you can include that in your custom code or any other piece of code that generates 17 character random strings from those characters I've given above, and use its outcome as your ID.

In fact, any other random string would suffice, as long as it is universally random, which Meteor's implementation tries to attain.

Upvotes: 4

Related Questions