Search code examples
javascriptangularfirebasegoogle-cloud-firestoreangularfire2

Get a subscollection of a collection with a where query


How do I get a subcollection of a collection with a where query? This is what I've done so far:

  getTasksByUserId(userId) {
    this.logger.debug(`Getting tasks by user id ${userId}`);
    if (userId) {
      return this.afs.collection('tasks', ref => ref.where('createdBy', '==', userId)).valueChanges();
    }
  }

My collection looks like this:

enter image description here

I'd like to also get the contents of features and tags in one query.


Solution

  • Firestore read operations (including queries) return documents from a single collection only. If you need to return results from multiple collections, you'll to perform at least one read operation for the documents from each of those collections.

    Consider if you really need the features and tags to be in subcollections, or whether they could also be (nested) fields in the document in the top-level tasks collection. If you do need them to be in the subcollections (for example for querying them), consider duplicating the data both in the task document, and in the subcollections.