1

I'm a bit confused how to use .set() with a transaction and get new document's ID. I'd like to save a new document and use the ID later in the transaction. I'm following this example how to add a document to the transaction.

const docRef = collectionRef.doc();
const result = await transaction.set(docRef, input);

Unfortunatelly, according to the docs transaction.set() returns transaction instance, not an actual documentSnapshot like transaction.get() would, so id can not be obtained from the result. Docs also say that you're supposed to perform all reads first and then all writes, so I don't believe that any set->get->set combination is a proper solution (also you need a ref for the get() anyway).

Is there a way to obtain new document's ID inside a Firestore's transaction without generating your own IDs?

Eggon
  • 2,032
  • 2
  • 19
  • 38

1 Answers1

2

Well, the simplest answers are sometimes the least obvious. It turns out that the docRef gets updated as a result of the transaction.set() and it contains the desired id. So to get id you just need to:

const docRef = collectionRef.doc();
const result = await transaction.set(docRef, input);
const id = docRef.id;
Eggon
  • 2,032
  • 2
  • 19
  • 38