I am trying to execute a transaction with a variable number of read operations. I put read () operations earlier than update ().
Reading a Firestore document at https://cloud.google.com/firestore/docs/manage-data/transactions
"A transaction consists of any number of get () operations, followed by any number of write operations, such as set (), update () or delete ()"
and
When using transactions, please note that:
- Read operations must be performed before write operations.
- The function that invokes the transaction (transaction function) can be executed more than once if the current editing affects the document that the transaction is reading.
- Transaction functions should not directly change the state of the application.
But implementation is not provided. When I try to run the code below, I understand that the transaction function is running more time, and then I get an exception. But if I try only one get everything goes OK.
const reservationCol = this.db.firestore.collection('reservations');
return this.db.firestore.runTransaction(t => {
return Promise.all([
t.get(reservationCol.doc('id1')),
t.get(reservationCol.doc(('id2')))]
).then((responses) => {
let found = false;
responses.forEach(resp => {
if (resp.exists)
found = true;
});
if (!found)
{
entity.id='id1';
t.set(reservationCol.doc(entity.id), entity);
return Promise.resolve('ok');
}
else
return Promise.reject('exist');
});
});
source
share