I’m trying to “move” a document from one collection to another in Firestore. That means copy/paste a document and then delete the original. I’m trying to achieve this server-side using Python.
I’m aware that using transactions might do the trick, but I’m wondering why couldn’t I just use a basic : .get() .set() and .delete() in order to do that? Because of another thread coming from another machine and modifying the document when I’m moving it ? Very unlikely in my case.
And then another question : why transaction and not a batch ? Since I’m copy/pasting the document, does that means that I’m reading it ?
Last point : do someone have a better example than the example from the docs ?
Advertisement
Answer
You are the best judge of what exactly you need.
As a generic answer you will need a transaction because:
If you don’t use a transaction, somebody may read the new document and the source document in an operation. Since you want to emulate a move operation, only the source OR the target document should ever exist – not both of them.
A user may modify the source document after your code read it, but when it didn’t yet write it. In this scenario, the transaction should fail and re-read the source document.
A batch won’t work for the same reason: you need to read the contents of the source document to write them to the destination. You could do this with a
get()
outside of the transaction, but then someone could modify it and your transaction wouldn’t detect that (since it only checks for documents that you read inside the transaction).
But you may have a special case where none of the above problems can apply, in which case: do for it. As a general rule though, this requires a transaction.