How to get the ID of a newly created document during a Transaction in Firestore?

Viewed 482

I'm reading the docs on Transaction operations, and I figured the t.set() method would work similar to the docReference.set() documented in the the Add data page.

To my surprise, it doesn't:

const newCustomerRef = db.collection('customers').doc();

await db.runTransaction(t => {
  const res = t.set(newCustomerRef, formData)
  console.log(res)
});

The res object above (return value of t.set()) contains a bunch of props that looks obfuscated, and it doesn't look as if it's intended for you to work with them.

Is there any way to get the ID of the newly created document within a Transaction?

Update

What I'm trying to achieve is to have multiple data operations in 1 go, and have everything reverted back if it fails.

As per Doug answer, if newCustomerRef already contains the ID, it seems what I am missing is to delete it during the catch block in case the transaction fails:

try {
  const newCustomerRef = db.collection('customers').doc();

  await db.runTransaction(t => {
    const res = t.set(newCustomerRef, formData)
    console.log(res)
  });
} catch (e) {
  newCustomerRef.delete()

  //...error handling...
}

This is sort of a manual thing to do, feels a little hacky. Is there a way to delete it automatically if the transaction fails?

2 Answers

newCustomerRef already contains the ID. It was generated randomly on the client as soon as doc() was called, before the transaction ever started.

const id = newCustomerRef.id

If a transaction fails for any reason, the database is unchanged.

The operation to add the document is performed in the set(..) call. This means by using set() on the transaction, everything is rolled back should the transaction fail.

This means in the following example

...
await db.runTransaction(t => {
    t.set(newCustomerRef, formData)
    ... do something ...

    if (someThingWentWrong) {
       throw 'some error'
    }
});

Should someThingWentWrong be true, no document will have been added.

Related