问题描述
如果您订购的内容没有唯一值,您是否会错过数据?
export async function getCities(){
const result = await firebase
.firestore()
.collection('cities')
.orderBy('population','desc')
.limit(5)
.get();
const CityResults = result.docs.map((city)=> ({
...city.data(),docId: city.id
}));
如果我限制为 5 并且我的最后一条数据的人口为 1000,我的 getMoreCities()
函数会说
startAfter(1000)
但假设有 7 个城市的人口恰好为 1000,那么您会错过两个 firestore 调用的数据。
你不能startAfter(documentId)
有解决方法吗?
解决方法
Firestore 将文档 ID 隐式添加到您指定锚文档的每个查询中,因此如果您传入 DocumentSnapshot
,它已经可以工作了。
您还应该能够将文档 ID 作为最后一个参数传递给您的 startAfter
变体,尽管我必须承认我自己总是为此目的使用 DocumentSnapshot
。
下面是一个示例:
citiesRef.orderBy("population").startAt(860000).limit(1).get().then((snapshot) => {
var lastdoc;
snapshot.forEach(function(doc) {
console.log("1: "+doc.id);
lastdoc = doc;
});
citiesRef.orderBy("population").startAfter(lastdoc).limit(1).get().then((snapshot) => {
snapshot.forEach(function(doc) {
console.log("2: "+doc.id);
lastdoc = doc;
});
});
});