简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM