2

I have just published an app that uses Firestore as a backend. I want to change how the data is structured; for example if some documents are stored in subcollections like 'PostsCollection/userId/SubcolletionPosts/postIdDocument' I want to move all this last postIdDocument inside the first collection 'PostsCollection'.

Obviously doing so would prevent users of the previous app version from writing and reading the right collection and all data would be lost.

Since I don't know how to approach this issue, I want to ask you what is the best approach that also big companies use when changing the data structure of their projects.

StackGU
  • 868
  • 9
  • 22

1 Answers1

1

So the approach I have used is document versioning. There is an explanation here.

You basically version your documents so when you app reads them, it knows how to update those documents to get them to the desired version. So in your case, you would have no version, and need to get to version 1, which means read the sub-collections to the top collection and remove the sub collection before working with the document.

Yes it is more work, but allows an iterative approach to document changes. And sometimes, a script is written to update to the desired state and new code is deployed . Which usually happens when someone wants it done yesterday. Which with many documents can have it's own issues.

Brettski
  • 19,351
  • 15
  • 74
  • 97
  • Great idea, thanks for the suggestions, so correct me If I'm wrong, in this use case: 1-read document and check if version is not present 2- in that case "move" the document inside the root collection 3- delete the subcollection document In this case we would end up in an hybrid case in which documents can be both in the subcollection and root collection. So we should make 2 queries instead of one – StackGU Aug 15 '21 at 23:13
  • 1
    Yes, in some cases you do end up with more queries. There are pros and cons to any solution. We have liked this one for its iterative approach to schema changes. When things get really big (millions of documents), it's nice to have such a structure in place. – Brettski Aug 16 '21 at 00:00