javascript - 在 Firebase 中使用 limit、orderBy 和 startAfter 时如何避免丢失数据?
问题描述
如果您订购的商品没有唯一值,您可能会错过数据,这不是真的吗?
例如,如果我有一个函数说:
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 人,那么您会错过两个消防站呼叫的数据。
看起来很傻,你不能startAfter(documentId)
有解决方法吗?
解决方案
Firestore 将文档 ID 隐式添加到您指定锚文档的每个查询中,因此如果您传入 aDocumentSnapshot
它已经可以工作。
您还应该能够将文档 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;
});
});
});
推荐阅读
- c++ - 如何在虚幻引擎 4 中添加 SWidgetSwitcher 并获取/设置当前小部件索引?
- html - 带有tailwindcss的侧边栏网格
- gremlin - Gremlin.Net,如何进行左外连接?
- python - pyorient 查询引发“ struct.error: required argument is not an integer”
- amazon-s3 - 在 cloudflare 工作人员中使用 aws4fetch 包调用 AWS api?
- v8 - 预加载器 V8 无服务器
- python - 模糊正则表达式:替换的模糊计数始终为 1
- javascript - 如何在 React 中使用 map 函数显示对象数组中的图像链接?
- flutter - RenderFlex 子级具有非零弹性,但传入的高度约束是无界的
- python - 根据一行中的关键字将csv分成几部分,然后转置