Home > Mobile >  How to move a firestore document from one collection to another
How to move a firestore document from one collection to another

Time:10-17

Is this possible to move a document from one collection to another in Firestore Database? The reason I want to do this is, when someone deletes an Order, I want to move it to deleted_orders collection rather than deleting the entire document to keep the history. I want to do this from my app which I have developed in Kotlin.

CodePudding user response:

The only way to move a document from one collection to another collection is to use the following sequence, mimicking a "cut & paste":

  1. Create a copy of the source document in the target collection, i.e. read it from the source collection, get the document fields and create a new document in the target collection with these fields, and then;
  2. Delete the document from the source collection.

In other words, there is no kind of "metadata" attached to a document that defines its parent collection and that you could change in one simple action.


Another approach would be to have all the order docs in a unique collection and a field which holds the order status, e.g. active or deleted. Then changing the order status is just a matter of updating a field.

Note that this approach will not have any negative effect on your queries performance since Firestore query performance is proportional to the size of the result set, not the data set size.

  • Related