1

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.

Tobias Kaufmann
  • 625
  • 1
  • 5
  • 19

1 Answers1

3

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Alright, thanks a lot, I was not aware of the immediate client side creation of the DocumentReference. – Tobias Kaufmann Feb 19 '21 at 18:07
  • If any method does not return a promise, then it is synchronous. The promise tells you that something is async, and the absence of a Promise is a clear signal that the work happens immediately. – Doug Stevenson Feb 19 '21 at 18:07