Database 在Firestore中查询后,如何获取集合中文档的名称?
我正在用Flatter编写一个应用程序,我希望能够根据特定条件查询Firestore集合中的一组文档,然后使用符合上述条件的文档获得这些文档的名称。这是我迄今为止尝试过的方法,但它不起作用Database 在Firestore中查询后,如何获取集合中文档的名称?,database,firebase,flutter,google-cloud-firestore,querying,Database,Firebase,Flutter,Google Cloud Firestore,Querying,我正在用Flatter编写一个应用程序,我希望能够根据特定条件查询Firestore集合中的一组文档,然后使用符合上述条件的文档获得这些文档的名称。这是我迄今为止尝试过的方法,但它不起作用 getDoc(String topic, int grade) { return Firestore.instance .collection('active') .where(topic, isEqualTo: true) .where('grade', isEqualTo:
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
执行查询时,在
然后的回调中得到的结果是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)
})
});
docRef
实际上不是文档引用。错误消息告诉您这是一个QuerySnapshot。您必须迭代其中的文档快照以了解它们。