Simon Z.
Simon Z.

Reputation: 497

Firestore Transaction Semantics With Read Queries

In the docs it is stated, that a transaction fails, when:

The transaction read a document that was modified outside of the transaction.

I'm wondering if this also applies to read queries, that might return more than one document (via .where('x', '==', 'y')). Does the transaction still fail, if the Read query would return more results if it was executed again sometime during the transaction?

To illustrate my question, let's say I have a collection of cars with the following Schema:

{ 
   ownerId: string, 
   make: string,
   horsepower: int
   ...
}

Now I'm querying the cars of a certain owner in a transaction.get() call:

transaction.get(firestore.collection('cars').where('ownerId', '==', '123'))...

Let's say I receive a Snapshot with 2 Cars, based on these cars I want to do some magic in the transaction. During the transaction another car is added for this owner (so it's not part of the initial Snapshot). Will the transaction fail in this case?

PS: I'm not looking for a different solution, the example above is fictitious, I just want to understand how the transaction behaves in this kind of case.

Upvotes: 2

Views: 514

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

Let's say I receive a Snapshot with 2 Cars, based on these cars I want to do some magic in the transaction. During the transaction another car is added for this owner (so it's not part of the initial Snapshot). Will the transaction fail in this case?

Definitely no. Since the new added car is not apart of the initial transaction, it won't fail. The car that is added is consider a new added object and not an object that was modified.

They mention in the docs that:

The transaction read a document that was modified outside of the transaction.

Because a transaction absolutely requires round trip communications with server in order to ensure that the code inside the transaction completes successfully. So that's why a transaction will fail if that particular document is modified by an operation other than the transaction in which is already involved.

Upvotes: 1

Related Questions