OrderBy和StartAt有两个不同的字段firestore



在我的应用程序中,我有一些注释的字段值为threadCommentCount。我想使用orderBy threadCommentCount降序对注释进行排序,然后使用startAfter(lastThreadCommentCount(继续分页。问题是,当threadCommentCount为0时,它每次都会返回相同的数据,因为它每次都从0开始。以下是查询:

popularCommentsQuery = db
.collection('comments')
.where('postId', '==', postId)
.orderBy('threadCommentCount', 'desc')
.startAfter(startAfter)
.limit(15)
.get()

一旦threadComment计数为0,这将每次返回相同的注释。我无法发送最后一个文档快照,因为我使用云功能,并且我不想在get查询参数中发送文档快照。我没有;我真的不在乎threadCommentCount为0后注释的顺序,我只需要不得到任何重复。任何帮助都很棒!

所有Firestore查询都有一个隐式orderBy("__name__", direction),用于解析其他命名orderBy字段具有相同值的文档之间的任何关系。这使得最终排序顺序稳定。但它也允许您将另一个参数传递给startAfter,以提供您希望用于分页的锚定文档的文档ID。

.startAfter(lastThreadCommentCount, lastDocumentId)

在这两个值之间,您应该能够在结果集中唯一地标识文档以启动下一页。

因此,我尝试在firestore中使用两个不同的字段(时间、键(的OrderBy和StartAfter来在flastList中建立分页。

关键是我们可以通过文档快照来定义查询光标[参考]

以下是我如何做到的。

步骤1:获取文档Id(由firebase自动生成(,其中(([reference]

const docRef = firestore().collection('shots').where('key','==','custom_key')
const fbDocIdGeneratedByFirebase= await docRef.get().docs[0].id;

步骤2:使用firebase生成的文档Id(我们在第一步中获得(获取文档快照

const docRef2= firestore().collection('shots').doc(fbDocIdGeneratedByFirebase)
const snapshot = await docRef2.get();

步骤3:将步骤2中获得的快照传递给startAfter((,以便光标指向那里[reference]

let additionalQuery =  firestore().collection('shots')
.orderBy("time", "desc")
.startAfter(snapshot)
.limit(this.state.limit)      
let documentSnapshots = await additionalQuery.get(); // you know what to do next
...    

您能改进解决方案吗

最新更新