在Firebase(Flutter)中访问嵌套的集合和文档

时间:2020-08-31 14:40:00

标签: firebase flutter dart google-cloud-firestore nosql

如果您看不懂标题,对不起。我是NoSQL的新手,不知道如何解决此问题。

我的Firebase数据库中有一个嵌套集合。 first collection

clicking on '145'

clicking on 'location'

在chargepoints方法中,我已经硬编码(.doc('WPHW9669')),而不是必须遍历145个集合并首先获取文档。之后,我必须进入该循环文档中才能访问“位置”集合。

这是需要修改的代码:

  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);
        }
      }
    });
  }

1 个答案:

答案 0 :(得分:0)

所以我找到了想要的答案。

我没有创建复杂的集合,而是将集合更改为简单。 新集合网址-145 /(公交车号)/位置/

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

上述方法将循环遍历'145'集合,并为找到的每个总线编号调用chargePoints()方法(我将总线编号注册为文档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);
          
        }
      }
    });
  }