Reputation: 856
Are operations in a batch write guaranteed to be executed in the order of their calling? it's not clear according to the docs. Is it forced to be only (#0) -> (#1) -> (#2) and not other way?
const batch = db.batch();
const nycRef = db.collection('cities').doc('NYC');
batch.set(nycRef, {name: 'New York City'}); // (#0)
const sfRef = db.collection('cities').doc('SF');
batch.update(sfRef, {population: 1000000}); // (#1)
const laRef = db.collection('cities').doc('LA');
batch.delete(laRef); // (#2)
return batch.commit().then(function () {
// ...
});
Upvotes: 5
Views: 1207
Reputation: 317362
The changes in a batch don't have an order. They happen atomically all at once, or not at all. There is no way any client could get a view of the database with an incomplete batch.
Any security rules that apply to documents the batch will see all documents changed at the same time. The security rules do not apply to individual documents in sequence. If you use getAfter() in security rules to fetch the contents of documents that were changed from the batch, each call to getAfter() will only ever see the new data.
There is never an intermediate state where documents updated from a batch appear to be incomplete.
If you have any Cloud Functions triggers on documents that could be updated by a batch, there is no defined order of execution - they could execute concurrently, or in some apparently "random" order.
Upvotes: 3
Reputation: 2048
As it is mentioned in the documentation :
A batch of writes completes atomically and can write to multiple documents.
From this I understand ( and I think this is how it should be, theoretically), that the operations from the same batch should happen in the same time, as a single one. Atomically.
EDIT Here there is an interesting article about how batch writes work. When you execute the commit, all the writes are executed in the same time ( theoretically, practically it is not possible ). When the status is completed and the commit is ready, than the collections should be modified. In general, in batch writes you cannot rely on the order they are actually executed, by default. For MongoDB, for example, I know that there are some methods to preserve the order( thing which is not happening by default). I was not able to find anything similar for Firestore, so I would say that, by default, you should not rely on the final order of the operations within a batch.
Upvotes: 2