How to Cloud Firestore Data Sort by Desc SwiftUI

Viewed 298

I am trying to fetch the data from my Firestore collection and now what i want to do is to sort the documents by one of the fields say "dateCode" Attaching codes below:

func getDescOrderData(completion: @escaping ([String:Any]) -> Void) {
    var dictInfo = [String:Any]()
    Firestore..collection("OldData").order(by: "dateCode", descending: true)
        .whereField("dateCode", isLessThanOrEqualTo: “Mon”)
        .whereField("studentId", isEqualTo: self.studentId)
        .getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Old History Data error: \(error.localizedDescription)")
                return
            }
            if let snapshot = querySnapshot {
                for document in snapshot.documents {
                        dictInfo.append(document.data())
                }
                completion(dictInfo)
            }
        }
}

But i got error given below:-

Old History Data error: The query requires an index. You can create it here: https://console.firebase.googl.................

Any help would be greatly appreciated.

1 Answers

The code is trying to use query which needs so called Composite Index. Actually according to the documentation it should be possible by the link that is in the error massage:

If you attempt a compound query with a range clause that doesn't map to an existing index, you receive an error. The error message includes a direct link to create the missing index in the Firebase console.

Just open it in browser and create the index. That's all! :)

Related