![](/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.