流星如何在客户端创建唯一的MongoDB _id? [英] How does Meteor create a unique MongoDB _id on the client side?

查看:111
本文介绍了流星如何在客户端创建唯一的MongoDB _id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据流星文档关于Mongo.Collection.insert()函数的信息,

插入将为您传递的对象生成一个唯一的ID,将其插入数据库中,然后返回ID.

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

它也可以异步工作:

如果提供回调,insert仍会立即返回ID.

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

是否可以保证所生成的_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软件包提供了几种用于生成随机数的功能 数字.它使用密码学上强的伪随机数 生成器(如果可能),但回退到较弱的随机数 密码强随机性不可用时的生成器 (在较旧的浏览器或没有足够熵的服务器上 播种加密强度高的生成器).

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])-返回唯一标识符,例如 "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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆