0

Let's say I am building an application where users can send emails. The emails are in one of three states/folders:

  1. Draft/Drafts
  2. Sending (waiting to be sent by the server)/Outbox
  3. Sent

Which of these approaches would be the most efficient (least resource intensive) and which one would be the preferred design in most use cases to store the emails in a Firestore database?

  1. There is an emails collection, inside of which are drafts, outbox, and sent sub-collections. As an email progresses through the three stages of progress the document is moved between each collection.
  2. The same concept as approach 1 however, each of the three sub-collections are root collections rather than sub-collections of an emails collection.
  3. There is an emails collection with all the documents from each state at the root of the collection. Each document has a status field/property which is set to either draft, sending, or sent.
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Jacob Wood
  • 209
  • 3
  • 13

2 Answers2

1

There's no singular best answer here, and it all depends on your use-cases and (here specifically) personal preferences.

Given Firestore's guarantee that the number of documents in a collection (or collection group) has no impact on the result of querying it, I'd probably go for a single collection as that requires the least modification of the data.

But that preference might change as you uncover more use-cases of your app.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

I also agree with @FrankvanPuffelen. Besides that, please also note that there is no "perfect", "the best" or "the correct" solution for structuring a Cloud Firestore database. So without knowing all the use-cases of your application, or better said, which are the queries that you need to perform, it's hard to say which one is better. However, among those three solutions, I would also choose the one in which I would save all emails into a single collection. Why? Because it's much, much cheaper.

If you want to move a document between two collections, please note that there is no straightforward solution that can help you achieve that. But you can easily solve it, by reading the document from the first collection, writing it in the second one, and deleting it from the original location. So you have to perform three operations. So imagine an email that gets through all three states, then you have to pay 9 operations. If you just update a property when the state changes, then you only have to pay three.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193