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

好久不见. 提交于 2020-01-16 02:51:08

问题


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?


回答1:


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

  • README for random package
  • random.js

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.



来源:https://stackoverflow.com/questions/33330886/how-does-meteor-create-a-unique-mongodb-id-on-the-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!