cloudwalker
cloudwalker

Reputation: 2466

Cloud Firestore: Best way to get collection with nested element references

Say that I have a collection called shoppingLists, and that collection contains a list of ingredients, where each of those ingredients is a reference to an ingredients collection. When retrieving a shoppinglist I need to also fetch some data from each of the ingredients. What is the best way to accomplish something like that? At the moment, I'm doing something like:

DocumentSnapshot userSnapshot = await Firestore.instance
      .collection('users')
      .document(userId)
      .collection('shoppingLists')
      .document(listName)
      .get();

And then I iterate over all of the ingredients in the collection and do:

DocumentReference ingredientReference = data['ingredient'];
DocumentSnapshot ingredientSnapshot = await ingredientReference.get();

to get down to the ingredient data. This is very slow, since I'm running a get query for each ingredient in the list. Is there some way to eagerly fetch this data when retrieving the shoppingLists collection so I just do one query?

Upvotes: 0

Views: 83

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You can't "join" collections in Firestore like you can in SQL. If you have multiple collections or subcollections to get documents from, you will need at least one query for each of those collections. There is no way to avoid this without restructuring your data.

If this is too slow for you, consider reorganizing your data in such a way that everything you need is in a single collection. This is not uncommon, and it often results in data duplication, which is OK.

Upvotes: 1

Related Questions