Search code examples
iosswiftfirebasegoogle-cloud-firestoreswift3

Firestore iOS - Ordering collection by field in document


I have an array called "homeList" which observers "CURRENT_USER_FRIENDS_REF" collection and places it in the array. How can I make it so I can order this array by the "timestamp" field found in the document snapshot.

homeList array function

    var homeList = [User]()

    func addHomeObserver(_ update: @escaping () -> Void) {
        CURRENT_USER_FRIENDS_REF.getDocuments { snapshot, error in
            self.homeList.removeAll()
            
            guard error == nil else {
                #if DEBUG
                    print("Error retrieving collection")
                #endif
                return
            }
            
            let group = DispatchGroup()
            
            for document in snapshot!.documents {
                let whosfrom = document.get("fromId") as? String
                let id = document.documentID
                **let timestamp = document.get("timestamp") as? NSNumber**
                group.enter()
                self.getUser(id, completion: { (user) in
                    if whosfrom != self.CURRENT_USER_ID {
                        self.homeList.append(user)
                    }
                    group.leave()
                })
            }
            
            group.notify(queue: .main) {
                update()
            }
        }
    }

Current user friends reference:

    var CURRENT_USER_FRIENDS_REF: CollectionReference {
        return CURRENT_USER_REF.collection("friends")
    }

Thanks.


Solution

  • You can use order(by on a collection reference to get the result.

    CURRENT_USER_FRIENDS_REF.order(by: "timestamp", descending: true).getDocuments { snapshot, error in
    
    }