Firestore如何将orderBy desC与startAfter(null)组合

时间:2019-02-24 01:03:21

标签: javascript firebase google-cloud-firestore angularfire2

我已经搜索了一段时间,但没有找到原因。

基本上,这会返回集合中的文档数组。

this.db.collection('people', ref => {
    return ref.orderBy(name, 'asc')
              .startAfter(null)
              .limit(10)
})...

这将返回一个空数组。

this.db.collection('people', ref => {
    return ref.orderBy(name, 'desc')
              .startAfter(null)
              .limit(10)
})...

唯一的区别是orderBy设置为'desc'。有人可以解释为什么会发生这种情况以及解决方法吗?预先感谢!

2 个答案:

答案 0 :(得分:1)

我认为问题是startAfter(null)。当您按升序排序时,空文档首先出现,然后是非空文档。有关确切的顺序,请参见Firebase documentation on the ordering of value types

当您按降序排序时,所有空文档都排在最后,因此空文档后没有任何内容可供查询返回。

我建议删除startAfter(null),直到您有相应的值为止。

答案 1 :(得分:0)

如果对我的解决方案感兴趣的人只需向上箭头:

var lastDocumentSnapshot : DocumentSnapshot? = null;
if (url != null){
    val query = this.getLastDocumentSnapshotAsync(url).await()
     if (!query.isEmpty){
        lastDocumentSnapshot = query.documents.distinct().first()
     }
}

val query = firebaseDb.collection("urls")
    .orderBy("name", sortDirection)
    .limit(limit)
if (sortDirection == Query.Direction.ASCENDING)
    query.startAfter(lastDocumentSnapshot)
else
    query.endBefore(lastDocumentSnapshot)

return query.get().asDeferredAsync()

不要介意代码的其他部分。基本上,解决方法是如果降序使用endBefore