1

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?

aedm
  • 5,596
  • 2
  • 32
  • 36
  • my guess is http://docs.meteor.com/#/full/random `Random.id([n])` is very similar –  Oct 25 '15 at 14:43
  • Probably like the official MongoDB https://docs.mongodb.org/manual/reference/object-id/ – str Oct 25 '15 at 15:47
  • If you mean, "how does the client know that the `_id` is not already taken on the server" then I bet it's a good chunk of maths and a bit of luck =p – Kyll Oct 25 '15 at 16:22

1 Answers1

3

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.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39