Chinmay Atrawalkar
Chinmay Atrawalkar

Reputation: 980

Firebase: How to update and get same document within one query?

I am using firebase to generate receipts for my app. To generate sequential receipt number to all receipts, i am maintaining a collection which has total number of receipts.

I am using firebase "increment" feature to increment total number of receipts by "1" and then again querying that document to get latest receipt number. Thus I am updating and getting same document.

Is there any other cleaner way where I don't have to query twice on same document?

Here is what I am doing so far:

code:

 admin
     .firestore()
     .collection("totalTransactions")
     .doc("total")
     .update({ total: admin.firestore.FieldValue.increment(1) })
     .then(() => {
         admin
             .firestore()
             .collection("totalTransactions")
             .doc("total")
             .get()
             .then((totalTxn) => {
                 const receiptNo = totalTxn.data().total;
             })
        })

Upvotes: 0

Views: 72

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598708

The only way to securely do this is by using a transaction. In that transaction you'll then:

  • Read the total document.
  • Write back the increased total value.
  • Write the receipt document.

This is the only way both writes either succeed or fail atomically.

Upvotes: 1

Related Questions