0
votes

My app provides the ability to query for a golf course based on state/location -- due to the data model i need to pull data from two different collections in Firestore. Currently the collections ("golfclub" contains location information and "courses" which has the course name I need to retrieve).

The two collections share a common field ("Facility ID") and have a many to one (courses -> golfclub) relationship. As in each golfclub may have 1 or more courses associated with it.

How would i go about creating a subcollection (clubcourses) that attachs each document from the existing course collection to the appropriate document in the golfclub collection based on the matching Facility ID?

My end result would be enable a query similar to the landmarks query for each city outlined in the collection group query docs. https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query

Existing Query in Dart without the collection group query;

void getFSCourseList() {
    List<String> facility = [];
    var clubQuery = golfClubDatabase
        .collection("golfclub")
        .where("State", isEqualTo: "$_selectedState");

    clubQuery.getDocuments().then((clubSnap) {
      if (clubSnap.documents.length > 0) {
        print('club docs length = ${clubSnap.documents.length}'); // sanity check

        clubSnap.documents.forEach((document) {
          facility.add(document.data[
              "Facility ID"]); //add the facilities to a temp list for use in next query
        });
        var courseQuery = golfCourseDatabase
            .collection("course")
            .where("Facility ID", arrayContainsAny: facility); // doesn't return a value for some reason...

        courseQuery.getDocuments().then((courseSnap) {
          print('length of course snap = ${courseSnap.documents.length}'); // sanity check should be longer than clubSnap.length
          if (courseSnap.documents.length > 0) {
            print('length of course snap = ${courseSnap.documents.length}');
          }
        });
        facility.forEach((fac) => print(fac)); // sanity check should equal club-snap.length
        //print(facility.length);
      } else {
        print("Not Found");
      }
    });
  }
1

1 Answers

0
votes

You have 2 options:

1) use the reference field in Firestore Documents to point to the document in the other collection.

2) Get the document reference in the first collection using a query, then in your code, manipulate the string so instead of pointing to the doc in the first collection, it will create a new doc at the new collection but following the same structure. From the same query you can event get all the data of the doc so no need for a 2nd query.

This example here if Firestore documentation might help (even if the purpose is different)