Reputation: 675
As specified in the Firebase documentation, .doc()
creates a unique ID.
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);
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?
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.
Upvotes: 1
Views: 686
Reputation: 317692
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.
Note that doc()
doesn't return the string ID directly - it returns a DocumentReference that contains the ID.
See also:
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.
Upvotes: 4