1
votes

Firestore transactions hold a pessimistic lock on the documents read in it. Does this lock apply even when the document doesn't exist?

Following the example from the nodejs docs:

firestore.runTransaction(transaction => {
  let documentRef = firestore.doc('col/doc');
  return transaction.get(documentRef).then(doc => {
    if (doc.exists) {
      transaction.update(documentRef, { count: doc.get('count') + 1 });
    } else {
      transaction.create(documentRef, { count: 1 });
    }
  });
});

If two transactions read and modify the same non-existing doc col/doc will one of them fail and attempt a rerun?

Also create method has it's own failure behavior - "The operation will fail the transaction if a document exists at the specified location.". Is the usage of create, compared to set+merge, safe in this context?

1

1 Answers

2
votes

In a general sense, if the contents of a document changes in after the document is read in the transaction, before it's written back in the same transaction, the transaction handler will be retried, and the new contents of the document will be seen on the retry.

In your specific case, the contents of documentRef changes, going to non-existent, to existent. I'd fully expect that to act like any other change on a document, and cause a transaction to retry if it suddenly existed where it didn't before.