0

I have a background service that is updating/removing/adding records in a Firestore collection to keep it in sync with another source of data.

Because performance, I want to do this in batches so I try to follow the official documentation.

But here is my question. When adding, I need to get the ID that Firestore is automatically generating for every add but I can not find a way to retrieve it.

So Is there a way? If there is not, what is the best way to generate me own IDs (ex. No idea if Firestore is using the ID as a hash to distribute the data)?

Regards

angelcervera
  • 3,699
  • 1
  • 40
  • 68

1 Answers1

2

Firestore doesn't automatically generate document IDs when working with batches. For each document in the batch, you must provide a DocumentReference, and that object contains the ID before anything happens.

You can generate an ID any way you want. They don't contain any data, and they are not hashes. They are just random characters, and are generated by the client app.

Read:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • @angelcervera You can call `document()` without any argument on a `CollectionReference` to have the Firestore SDK generate the ID. This API does not perform any interaction with the database backend, so you can use it inside the transaction - and then use the resulting `DocumentReference` in the transaction to write to it transactionally. --- https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/CollectionReference#document() – Frank van Puffelen Jun 04 '23 at 13:57
  • @FrankvanPuffelen So doing a transaction instead a batch will result in the same performance and cost? – angelcervera Jun 04 '23 at 15:58
  • 1
    Frank was not saying anything about any differences between transactions and batches. He was just saying that you can generate a document ID using the SDK at basically no cost since it all happens on the client app and doesn't interact with the database at all. – Doug Stevenson Jun 04 '23 at 16:06
  • I can see that now. Got it. Thanks everybody – angelcervera Jun 04 '23 at 17:06
  • Oops, sorry for the the confusion - and thanks for clarifying, Doug! – Frank van Puffelen Jun 04 '23 at 17:49