首页 > 解决方案 > Firestore Android Orderby Descending 不工作

问题描述

所以,我有一个 firestore 集合,我想按降序获取数据,但它不起作用。结果总是给出一个空列表。但不知何故,如果我将排序方向更改为升序,查询就可以完美运行。这是他的代码:

    fun getComments(uid: String, category: String, postId: String, limit: Long , startAt : Timestamp?, listener: GenericGetListener<List<CommentModel>>) {
        val collectionPath = getCollectionPath(category)
        if (collectionPath == null) {
            listener.onError(Exception("Not valid"))
            return
        }
        val commentListRef = db.collection("${collectionPath}/$postId/comments")
        commentListRef
                .orderBy("timestamp", Query.Direction.DESCENDING)
                .limit(limit)
                .startAt(startAt)
                .get()
                .addOnSuccessListener { querySnapshot ->
                    val commentList = querySnapshot.toObjects(CommentModel::class.java)
                    db.runTransaction { transaction ->
                        return@runTransaction commentList.map {  commentModel ->
                            val userUid = commentModel.uid
                            if(userUid != null){
                                val user = transaction.get(
                                        db.collection(CollectionsPath.users).document(userUid)
                                ).toObject(UserProfileModel::class.java)
                                if(user != null){
                                    commentModel.apply {
                                        this.profilePic = user.profilePic
                                        this.name = user.name
                                        this.verifiedStatus = user.verifiedStatus
                                        this.accCategory = user.accType
                                        this.subAccType = user.subAccType
                                        this.category = user.category
                                    }
                                }

                            }
                            commentModel
                        }
                    }.addOnSuccessListener {
                        listener.onSuccess(it)
                    }.addOnFailureListener {
                        listener.onError(it)            
                    }
                }
                .addOnFailureListener {
     
                    listener.onError(it)
                }


    }

firestore 集合是一个嵌套集合,具有这种结构 post->postId->comment

这就是firestore集合的样子 在此处输入图像描述

标签: androidfirebasekotlingoogle-cloud-firestore

解决方案


推荐阅读