gbhall
gbhall

Reputation: 13279

Cloud Firestore fetch multiple documents at once

I am building an app that has Users, Sports Teams and Articles.

A user can follow any sports team and within that sports team some users will be contributors and post articles for the followers to see.

A million users could follow the same sports team, but only a few users, e.g. 10, would be contributors who can post articles about that particular sports team.

Reading up on Firestore, I may be inclined to structure my data in the following way:

E.g. Structure:

From my understanding if I want to perform a query to list all Sports Teams for those that I am a contributor for, I would simply do a fetch on Sports Teams where('contributingUsersIDs.someUserID', '==', true).

Question: How are you meant to do a simple query to retrieve the list of all the Sports Teams documents you as a particular user follow? In Datastore I'd simply do ofy().load().keys(followingSportsTeamsIDsKeys).values().

Is the proper solution to simply do a fetch to retrieve all the followingSportsTeamsIDs a user has, then if say they follow a thousand different Sports Teams to simply do db.collection("teams").document("someTeamID").getDocument and make a request for each ID in a for loop on the client? That seems excessive? But maybe not because Firestore remains a persistent connection?

Or, how am I meant to restructure my data for Firestore?

Upvotes: 3

Views: 2244

Answers (1)

Sam Stern
Sam Stern

Reputation: 25134

There is no way to fetch multiple documents at once with Cloud Firestore (for now).

You're right, these type of joins can become pretty inefficient if you have to do the requests in a loop. It's not as bad as if you were making a separate HTTP call for each one (as you said, they'll share a connection) but it's not great.

Instead you may want to duplicate some data. For example if you have a screen where the user can see each team they follow, maybe you only need the team name for each one on that screen. In that case you could make users look like this:

{

  username: "whatever",
  teams: [
    {
      id: "team_1",
      name: "Team One"
    }
    ...
  ]
}

This is one of the tradeoffs you have to make when using a NoSQL database. Optimize your data structure for how it will be used!

Upvotes: 1

Related Questions