I'm trying to run a transaction with a variable number of read operations. I put the read () operations before than update ().
Reading the Firestore doc on 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, note that:
- Read operations must come before write operations.
- A function calling a transaction (transaction function) might run more than once if a current edit affects a document that the transaction reads.
- Transaction functions should not directly modify application state.
But is not provided an implementation. When I try to run the code below, I get that the transaction function is runned more time and then I obtain an exception. But if I try with only one get all 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');
});
});