如何按单个页面分页Firestore数据集? [英] How to paginate Firestore dataset by individual page?

查看:51
本文介绍了如何按单个页面分页Firestore数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按20个项目的页面对存储在Firebase中的论坛帖子进行分页,如下所示:

I want to paginate my forum posts stored in Firebase by pages of 20 items, like so:

  • 用户访问foo.com/1->最近有20条帖子已加载
  • 用户访问foo.com/2->帖子21-40已加载

以此类推.

现在,我知道我可以使用查询游标(如所述在这里),例如无限滚动,因为在那里我从1-> 2-> 3页开始,依此类推,并且每次我在 .startAfter(lastVisible)方法中可以引用的最后一个可见文档时.

Now I am aware I can work with query cursors (as mentioned here), which works perfectly fine for e.g. infinite scroll, because there I start with page 1->2->3 and so on, and each time I have the last visible document available to reference to in my .startAfter(lastVisible) method.

但是,如果我希望用户能够访问例如第13页直接查看文章241-260?有没有一种方法可以从页面文档241开始,而无需先进行(多个)查询才能获取lastVisible文档?

But what if I want users to be able to access e.g. page 13 to see posts 241-260 directly? Is there a way to start at page document 241, without doing (multiple) queries first to get the lastVisible documents?

添加:

这可能非常糟糕,因此请谨慎实施以下内容.我找到了以下方法来解决"此问题:

This is probably very bad, so be carful in implementing the below. I found following way to "solve" this issue:

const pageNo = 1 /* variable */
const postsPerPage = 20

const baseRef = fireDb.collection("posts")

let currentPageRef

if (pageNo === 1) {
  currentPageRef = baseRef.limit(postsPerPage)

} else {

  let lastVisibleRef = baseRef.limit((pageNo-1) * postsPerPage)
  const lastVisibleQuerySnapshot = await lastVisibleRef.get()
  const lastVisiblePost = lastVisibleQuerySnapshot.docs[lastVisibleQuerySnapshot.docs.length-1]

  currentPageRef = baseRef.startAfter(lastVisiblePost).limit(postsPerPage)
}
const currentPageQuerySnapshot = await currentPageRef.get()

这需要两个查询.但是它实现了我想要实现的目标.谁能判断该解决方案的效率/计费有多糟糕?例如.如果有人可以访问第999页,我担心那会花很多钱吗?

That needs two queries. But it achieves what I want to achieve. Can anyone judge how bad that solution is efficiency/billing? E.g. if someone would access page 999 I fear that will be costly?

推荐答案

使用Firestore客户端SDK时,无法在查询结果中指定偏移量.您可以在GitHub上阅读有关此内容的讨论.

With the Firestore client SDKs, there is no ability to specify an offset into query results. You can read a discussion about this on GitHub.

服务器SDK确实具有偏移量,但是.

The server SDKs do have offset, however.

这篇关于如何按单个页面分页Firestore数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆