在Firestore中查询后如何获取集合中文档的名称?
How to get the name of a document in a collection after querying in Firestore?
我正在用 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
当您执行查询时,您在 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)
})
});
我正在用 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
当您执行查询时,您在 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)
})
});