我正在尝试在 firestore 中应用分页,我需要从我的 hats 文档中的 items 数组中获取前 5 项(总共 200 项) collections 集合,然后在下次单击时我需要获取下 5 个,依此类推。
testPagination = async () => {
const { currentPage, itemsPerPage } = this.state;
const { fetchCollectionsForPagesStart, match : { params } } = this.props;
const collectionId = params.collectionId;
const startAt = currentPage * itemsPerPage - itemsPerPage;
const docs = await firestore.collection("collections").orderBy('id').startAt(0).limit(itemsPerPage).get();
const data = docs.docs;
const items = docs.forEach( async docItem => {
console.log(await docItem.data());
})
}
当我单击 React 内渲染函数中的按钮时,我运行此函数,
render()
{
return (
<button onClick={this.testPagination}>Test pagination </button>
);
}
但我的结果中总是收到 200 个项目,那么如何将 startAt() 和 limit() 应用于 firestore 中的项目数组。
这是我的数据库:
这个console.log(await docItem.data());给我
注意:我正在收到帽子文档 ID,因此,如果有一种方法可以访问带有 id 的帽子,我也尝试过,因此需要一些帮助
const docs = await firestore.doc(`collections/${collectionId}`).get();
const data = await docs.data();
但这不允许我应用 startAt() 和 limit()
最佳答案
在你的数据库中,hats
是collections
集合的文档。在 Firestore 中,您无法引入文档的一部分(例如,items
数组中的 5 个项目),但始终会引入整个文档,并且在 Firestore 中将其算作一次读取。
如果要对 items
数组进行分页,则必须在 hats
中使用 items
上的数据创建子集合。有了这个结构,您就可以执行 startAtQuery()
,limit()
为 5 个文档,在本例中,它在 Firestore 中算作 5 次读取。
您可以在此处查看有关 Firestore 数据模型的所有信息:https://firebase.google.com/docs/firestore/data-model
关于javascript - 如何将 limit 和 startAt 应用于 firestore 文档的子项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60894887/