aedm
aedm

Reputation: 6564

How does Meteor create a unique MongoDB _id on the client side?

According to Meteor docs about the Mongo.Collection.insert() function,

insert will generate a unique ID for the object you pass, insert it in the database, and return the ID.

It also works asynchronously:

If you do provide a callback, insert still returns the ID immediately.

Is there any guarantee that the generated _id is globally unique? How does Meteor's Minimongo generate such an _id on the client side?

Upvotes: 1

Views: 2762

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

As Meteor is open source you can see exactly how this is done.

From the README:

The random package provides several functions for generating random numbers. It uses a cryptographically strong pseudorandom number generator when possible, but falls back to a weaker random number generator when cryptographically strong randomness is not available (on older browsers or on servers that don't have enough entropy to seed the cryptographically strong generator).

Random.id([n]) - Returns a unique identifier, such as "Jjwjg6gouWLXhMGKW", that is likely to be unique in the whole world. The optional argument n specifies the length of the identifier in characters and defaults to 17.

The short answer is that Meteor uses cryptography (aka maths as per @Kyll) to generate a random id that should be globally unique across all objects in all mongo databases everywhere. The "luck" part is that there is a small chance that two objects could end up with the same id. Now the _id key is indexed unique in mongo so an insert would fail if there is a dupe. I suspect Meteor has error handling to deal with that possibility.

Upvotes: 3

Related Questions