5

I'm planning the structure of my DB for a project using Cloud Firestore, and I'm currently trying to figure out the best approach to storing data and associating it to users. The specifics are as follows:

I have a collection of user documents at the root of my DB, and I want users to be able to make posts that are accessible both by looking at a user profile page which displays posts by that user, and in aggregate by looking at a page displaying posts by all users.

Storing a user's posts in a sub-collection of the user document would make it very easy to fetch a user's posts for their profile, but is it possible to write an elegant query that merges every user's post sub-collections into one result set?

Or would a better approach to be to have another collection in the root of my called posts, and have a field on each post containing the user's UID or a denormalized copy of the user document?

saricden
  • 2,084
  • 4
  • 29
  • 40

1 Answers1

3

A query runs against a single document collection. There is (currently) no way to query across multiple (sub)collections.

That means you'll probably want to keep the user documents in a top-level documents collection, with a owner property for their UIDs. Then you can select a user's post with a simple documentsRef.where("owner", "==", uid).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 3
    This is now possible with collection group queries. See https://stackoverflow.com/a/46573167/6253640 for more details. – Gil Gilbert May 07 '19 at 18:53