![](/img/trans.png)
[英]How do I get all documents in a Cloud Firestore collection using Version 9 of the Modular Web SDK?
[英]How do I know if there are more documents left to get from a firestore collection?
我正在使用 flutter 和 firebase。我使用分页,每页最多 5 个文档。 我怎么知道是否还有更多文档需要从 Firestore 集合中获取。 我想使用此信息来启用/禁用呈现给用户的下一页按钮。
限制:5(每次5个文件)
orderBy:“日期”(最新的优先)
startAfterDocument: latestDocument(只是一个保存最新文档的变量)
这就是我获取文件的方式。
collection.limit(5).orderBy("date", descending: true).startAfterDocument(latestDocument).get()
我考虑过检查从 firestore 收到的文档数量是否等于 5,然后假设有更多文档要获取。 但是如果我在集合中总共有 n * 5 个文档,这将不起作用。
我考虑过获取集合中的最后一个文档并存储它,并将它与我得到的批次中的每个文档进行比较,如果有匹配项,那么我知道我已经读完了,但这意味着阅读过多。
或者,也许我可以继续获取文档,直到我得到一个空列表并假设我已经到达集合的末尾。
我仍然觉得有更好的解决方案。
如果您需要更多信息,请告诉我,这是我关于此帐户的第一个问题。
响应中没有标志表明还有更多文档。 常见的解决方案是请求比您需要/显示的文档多一个文档,然后使用最后一个文档的存在作为存在更多文档的指示符。
这也是数据库在其响应中包含此类标志所必须执行的操作,这可能就是为什么这不是 SDK 中的显式选项的原因。
您可能还想查看有关 保持集合中文档数量的分布式计数的文档,因为这是确定是否需要启用 UI 以加载下一页的另一种方法。
这是从 firebase 集合中获取大量数据的方法
let latestDoc = null; // this is to store the last doc from a query
//result
const dataArr = []; // this is to store the data getting from firestore
let loadMore = true; // this is to check if there's more data or no
const initialQuery = async () => {
const first = db
.collection("recipes-test")
.orderBy("title")
.startAfter(latestDoc || 0)
.limit(10);
const data = await first.get();
data.docs.forEach((doc) => {
// console.log("doc.data", doc.data());
dataArr.push(doc.data()); // pushing the data into the array
});
//! update latest doc
latestDoc = data.docs[data.docs.length - 1];
//! unattach event listeners if no more docs
if (data.empty) {
loadMore = false;
}
};
// running this through this function so we can actual await for the
//docs to get from firebase
const run = async () => {
// looping until we get all the docs
while (loadMore) {
console.log({ loadMore });
await initialQuery();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.