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

查看:78
本文介绍了是否可以使用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的方法,则可以随意以某种方式自行生成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天全站免登陆