问题描述
根据流星文档关于Mongo.Collection.insert()
函数的信息,
它也可以异步工作:
是否可以保证所生成的_id是全局唯一的?流星的Minimongo如何在客户端生成这样的_id?
Is there any guarantee that the generated _id is globally unique? How does Meteor's Minimongo generate such an _id on the client side?
推荐答案
由于Meteor是开源的,因此您可以确切地看到它是如何完成的.
As Meteor is open source you can see exactly how this is done.
- README for random package
- random.js
自述文件:
Random.id([n])
-返回唯一标识符,例如 "Jjwjg6gouWLXhMGKW",在全世界很可能是唯一的. 可选参数n指定标识符的长度 字符,默认为17.
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.
简短的答案是,流星使用加密技术(根据@Kyll,又名数学)生成一个随机ID,该ID在全球所有mongo数据库中的所有对象之间应是全局唯一的. 运气"部分是,两个对象最终具有相同id的可能性很小.现在_id
键在mongo中被索引为唯一,因此如果存在重复,则插入将失败.我怀疑Meteor可以通过错误处理来解决这种可能性.
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.
这篇关于流星如何在客户端创建唯一的MongoDB _id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!