【问题标题】:How to get the name of a document in a collection after querying in Firestore?在 Firestore 中查询后如何获取集合中文档的名称?
【发布时间】:2020-07-08 18:31:45
【问题描述】:

我正在 Flutter 中编写应用程序,我希望能够根据特定条件查询 Firestore 集合中的一组文档,然后使用符合所述条件的文档获取这些文档的名称。这是我迄今为止尝试过的,但它不起作用。

 getDoc(String topic, int grade) {
  return Firestore.instance
    .collection('active')
    .where(topic, isEqualTo: true)
    .where('grade', isEqualTo: grade)
    .getDocuments()
    .then((docRef) {
      return docRef.id;
    });
  }

除了我调用 docRef.id 的部分之外,所有代码都有效。当我调用 docRef.id 时,我收到一条错误消息:

The getter 'id' isn't defined for the class 'QuerySnapshot'.
Try importing the library that defines 'id', correcting the name to the name of an existing getter, or defining a getter or field named 'id'.d

【问题讨论】:

  • docRef 实际上不是 DocumentReference。错误消息告诉您它是一个 QuerySnapshot。您必须迭代其中的文档快照以了解它们。

标签: database firebase flutter google-cloud-firestore querying


【解决方案1】:

当您执行查询时,您在then 回调中得到的结果是QuerySnapshot。即使只有一个文档符合条件,您也会得到一个QuerySnapshot,其中包含一个文档。要获得作为结果的单个 DocumentSnapshot,您需要遍历 QuerySnapshot.documents

类似:

Firestore.instance
    .collection('active')
    .where(topic, isEqualTo: true)
    .where('grade', isEqualTo: grade)
    .getDocuments()
    .then((querySnapshot) {
      querySnapshot.documens.forEach((doc) {
        print(doc.documentID)
      })
    });

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 2022-08-20
    • 2021-05-17
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多