【发布时间】:2019-04-20 12:20:31
【问题描述】:
我正在构建一个颤振应用程序并使用 Cloud Firestore。我想获取数据库中所有文档的数量。
我试过了
Firestore.instance.collection('products').toString().length
但是没有用。
【问题讨论】:
标签: firebase dart flutter google-cloud-firestore
我正在构建一个颤振应用程序并使用 Cloud Firestore。我想获取数据库中所有文档的数量。
我试过了
Firestore.instance.collection('products').toString().length
但是没有用。
【问题讨论】:
标签: firebase dart flutter google-cloud-firestore
应该是 - Firestore.instance.collection('products').snapshots().length.toString();
【讨论】:
Firebase 并没有官方提供任何函数来检索集合中的文档数量,而是您可以获取集合的所有文档并获取它的长度..
有两种方式:
1)
final int documents = await Firestore.instance.collection('products').snapshots().length;
这将返回一个 int 值。但是,如果你不使用 await,它会返回一个 Future。
2)
final QuerySnapshot qSnap = await Firestore.instance.collection('products').getDocuments();
final int documents = qSnap.documents.length;
这将返回一个 int 值。
但是,这两种方法都会获取集合中的所有文档并对其进行计数。
谢谢
【讨论】:
首先,您必须从该集合中获取所有文档,然后您可以通过文档列表获取所有文档的长度。下面应该可以完成工作。
Firestore.instance.collection('products').getDocuments.then((myDocuments){
print("${myDocuments.documents.length}");
});
【讨论】:
由于您正在等待未来,因此必须将其放在异步函数中
QuerySnapshot productCollection = await
Firestore.instance.collection('products').get();
int productCount = productCollection.size();
集合中的文档数量
【讨论】:
Future getCount({String id}) async => FirebaseFirestore.instance
.collection(collection) //your collectionref
.where('deleted', isEqualTo: false)
.get()
.then((value) {
var count = 0;
count = value.docs.length;
return count;
});
这是飞镖语言...
【讨论】:
Firestore.instance
.collection("products")
.get()
.then((QuerySnapshot querySnapshot) {
print(querySnapshot.docs.length);
});
【讨论】:
以上建议将导致客户端下载集合中的所有文档以获取计数。作为一种解决方法,如果您的写入操作不经常发生,您可以将文档的长度放到 Firebase 远程配置中,并在您从 Firestore 集合中添加/删除文档时更改它。然后,您可以在需要时从 firebase 远程配置中获取长度。
【讨论】: