是否可以使用 Firebase .doc() 接收重复的 ID? [英] Is it possible to receive duplicate IDs with Firebase .doc()?

查看:30
本文介绍了是否可以使用 Firebase .doc() 接收重复的 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase 文档中所述,.doc() 创建唯一 ID.

As specified in the Firebase documentation, .doc() creates a unique ID.

我通过以下方式为 Firestore 创建新文档(注意 session.docId 应该等于实际的文档 ID,我使用的是 AngularFire 语法):

I create new documents for Firestore the following way (note that session.docId should be equal to the actual document ID and I am using AngularFire syntax):

const id = db.createId();
const session = { docId: id, name: "test" };
this.db.collection("sessions").doc(id).set(session);

.doc() 是否保证上述工作流程始终有效(意味着 id 将始终是唯一的)?假设我有一个充满会话的数组(例如 10000 个项目)——我遍历这个数组并按照我上面指定的方式为每个项目创建一个会话文档.考虑到 Javascript 的异步特性,我非常怀疑这是否会在某些时候产生重复的 ID(尽管由于 docId 的长度等原因,这种可能性很小).或者 .doc() 保留"吗?限定时间内的 ID?

Does .doc() guarantee that the above workflow will always work (meaning that id will always be unique)? Let's assume I have an array full of sessions (e.g. 10000 items) - I iterate over this array and create a session document for each item the way I specified it above. Considering the asynchronous nature of Javascript, I am very sceptical if this might produce a duplicate ID at some point (although very unlikely due to the length etc. of the docId). Or does .doc() "reserve" the ID for a limited amount of time?

我知道我也可以通过 .add() 创建一个新文档,然后通过 .set() 更新 docId,但这种方法需要 2 次写入操作,而且速度也会慢一些.

I am aware that I could also create a new document via .add() and update the docId afterwards via .set(), but this method would need 2 write operations and would also be way slower.

推荐答案

doc() 总是在客户端应用程序上立即生成一个带有随机 ID 的 DocumentReference(非异步)这几乎可以保证是独一无二的.两个 ID 之间发生冲突的几率是天文数字.它实际上与调用 add() 相同,只是它实际上不是同时创建文档.

doc() always generates a DocumentReference with random ID immediately on the client app (not asynchronously) that is virtually guaranteed to be unique. The chance of collision between two IDs is astronomically low. It's effectively the same thing as calling add(), except it is not actually creating the document at the same time.

请注意,doc() 不直接返回字符串 ID - 它返回包含 ID 的 DocumentReference.

Note that doc() doesn't return the string ID directly - it returns a DocumentReference that contains the ID.

另见:

如果由于某种原因您不信任这种生成 ID 的方法,您可以以某种方式自行生成它们.它只是一个字符串.

If for some reason you do not trust this method of generating IDs, you are free to generate them yourself somehow. It's just a string.

这篇关于是否可以使用 Firebase .doc() 接收重复的 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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