Reputation: 980
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
Reputation: 598708
The only way to securely do this is by using a transaction. In that transaction you'll then:
total
document.total
value.This is the only way both writes either succeed or fail atomically.
Upvotes: 1