-5

I have the following data in cloud firestore:

/Tasks

  • id

  • name: string

  • description: string

  • assignees (collection of assignees inside each task)

When in query for my tasks, I only get the basic data like name, description. But not the assignees-collection inside a task. Is there a way to fetch the 'whole' task document/object with a single read?

I don't want to do a '[taskId]/assignees' fetch for each task.

  • 3
    Does this answer your question? [Cloud Firestore deep get with subcollection](https://stackoverflow.com/questions/46611279/cloud-firestore-deep-get-with-subcollection) – Soni Sol May 25 '21 at 23:07

1 Answers1

1

I don't know what your platform is but accessing a subcollection is just a matter of defining the path to that collection.

For example if you wanted to access the assignees subcollection the path could be defined like this (Swift, but the concept is the same across platforms)

let tasksCollectionRef = self.db.collection("Tasks")
let taskDocRef = collectionRef.document("some task id")
let assigneesSubCollectionRef = userDoc.collection("assignees")

assigneesSubCollectionRef(completion: { documentSnapshot, error in
    //do somethingn with the documents within assignees

I don't want to do a '[taskId]/assignees' fetch for each task.

So you can either handle it in code by doing just that with this kind of code flow

iterate over tasks
   read the assignees collection for each task

or you can change your model and store the assignees within each task. You could use an array, or even a map to enclose the assignees

task_id          //document
   assignees     //map
      assignee_0 //map
         name    //field
      assignee_1 //map
         name    //field

And when the task document is read the assignees will be a field that can be read. Here I am reading the assignees field into an array of dictionaries and iterating over them

let assignees = doc.get("assignees") as! [String: Any]
for a in assignees {
   print(a.key, a.value)
}
Jay
  • 34,438
  • 18
  • 52
  • 81