Meteor 如何在客户端创建一个唯一的 MongoDB _id?
How does Meteor create a unique MongoDB _id on the client side?
根据Meteor docs关于Mongo.Collection.insert()
函数,
insert will generate a unique ID for the object you pass, insert it in the database, and return the ID.
它也可以异步工作:
If you do provide a callback, insert still returns the ID immediately.
是否可以保证生成的_id 是全局唯一的? Meteor的Minimongo是如何在客户端生成这样的_id的?
由于 Meteor 是开源的,您可以确切地看到这是如何完成的。
来自自述文件:
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.
简短的回答是 Meteor 使用密码学(又名 maths 根据@Kyll)生成一个随机 ID,该 ID 在所有 mongo 数据库无处不在。 "luck" 部分是两个对象最终具有相同 id 的可能性很小。现在 _id
键在 mongo 中的索引是唯一的,因此如果存在欺骗,插入将失败。我怀疑 Meteor 有错误处理来处理这种可能性。
根据Meteor docs关于Mongo.Collection.insert()
函数,
insert will generate a unique ID for the object you pass, insert it in the database, and return the ID.
它也可以异步工作:
If you do provide a callback, insert still returns the ID immediately.
是否可以保证生成的_id 是全局唯一的? Meteor的Minimongo是如何在客户端生成这样的_id的?
由于 Meteor 是开源的,您可以确切地看到这是如何完成的。
来自自述文件:
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.
简短的回答是 Meteor 使用密码学(又名 maths 根据@Kyll)生成一个随机 ID,该 ID 在所有 mongo 数据库无处不在。 "luck" 部分是两个对象最终具有相同 id 的可能性很小。现在 _id
键在 mongo 中的索引是唯一的,因此如果存在欺骗,插入将失败。我怀疑 Meteor 有错误处理来处理这种可能性。