【问题标题】:Accessing nested collections and document in Firebase (Flutter)在 Firebase (Flutter) 中访问嵌套集合和文档
【发布时间】:2020-12-19 16:44:55
【问题描述】:

如果您无法理解标题,我非常抱歉。我是 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);
        }
      }
    });
  }

【问题讨论】:

  • 你有什么问题?到目前为止,您有什么问题?
  • @Doug Stevenson 在 Chargepoints 方法中我已经硬编码 (.doc('WPHW9669')) 而不是我必须遍历 145 集合并首先获取文档,然后我必须进入该循环文档以访问“位置”集合
  • 请编辑问题以更清楚地了解问题所在 - 不要只在 cmets 中留下信息。底部有编辑链接。
  • 我已经更新了@DougStevenson

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


【解决方案1】:

所以我找到了我正在寻找的答案。

我没有创建一个复杂的集合,而是将我的集合更改为简单。 新集合 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);
      });
    });
  }

上述方法将遍历'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);
          
        }
      }
    });
  }

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2018-09-19
    • 2021-09-29
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多