Sendduran Thailan
Sendduran Thailan

Reputation: 13

Accessing nested collections and document in Firebase (Flutter)

If you cannot understand the title I am very sorry. I am new to NoSQL don't know how to address this problem.

i am having a nested collection inside my firebase database. first collection

clicking on '145'

clicking on 'location'

in the chargepoints method I have hardcoded (.doc('WPHW9669')) instead of that I have to loop through the 145 collection and get the document first. after that I have to go inside that looped document to access the 'location' collection.

this is the code which needs to be modified:

  chargePoints() {
    _db
        .collection('bus')
        .doc('Routes')
        .collection('145')
        .doc('WPHW9669') // this the place where the first iteration have to occur
        .collection('location')
        .orderBy('updatedTime', descending: true)
        .limit(1)
        .get()
        .then((docs) {
      if (docs.docs.isNotEmpty) {
        for (int i = 0; i < docs.docs.length; i++) {
          LatLng position = LatLng(
              docs.docs[i].data()['position']['geopoint'].latitude,
              docs.docs[i].data()['position']['geopoint'].longitude);
          print(docs.docs[i].data()['position']['geopoint'].latitude);
          initMarker(position, docs.docs[i].id);
          // notifyListeners();
          // initMarker(docs.docs[i].data(), docs.docs[i].id);
        }
      }
    });
  }

Upvotes: 0

Views: 2129

Answers (1)

Sendduran Thailan
Sendduran Thailan

Reputation: 13

So I found the answer that I am looking for.

instead of creating a complicated collection, I change my collection to be simple. new collection URL - 145/(Bus NO)/location/

    final result = FirebaseFirestore.instance.collection('145');
  busPoint() {
    result.get().then((snapshot) {
      snapshot.docs.forEach((element) {
        chargePoints(element.id.toString());
        print(element.id);
      });
    });
  }

the above method will loop through the '145' collection and call the chargePoints() method for each bus no's found(i registered the bus no as the document id).

  chargePoints(String element) {
    _db
        .collection('145')
        .doc(element) 
        .collection('location')
        .orderBy('updatedTime', descending: true)
        .limit(1)
        .get()
        .then((docs) {
      if (docs.docs.isNotEmpty) {
        for (int i = 0; i < docs.docs.length; i++) {
          LatLng position = LatLng(
              docs.docs[i].data()['position']['geopoint'].latitude,
              docs.docs[i].data()['position']['geopoint'].longitude);          
          initMarker(position, docs.docs[i].id);
          
        }
      }
    });
  }

Upvotes: 1

Related Questions