Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

python - How to move a document between 2 collections in Firebase?

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 ?

question from:https://stackoverflow.com/questions/65945300/how-to-move-a-document-between-2-collections-in-firebase

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...