Gurkarn Goindi
Gurkarn Goindi

Reputation: 79

Swift 5 Firestore: Checking if collection exists in database

I'm trying to check if a certain collection exists in my Firestore database, and here is my code for doing so:

let db = Firestore.firestore()
                db.collection(pickedClass).getDocuments { (snapshot, error) in

                    if error == nil && snapshot != nil {
                        if snapshot!.documents.count > 0 {

                        for document in snapshot!.documents {
                            let documentData = document.data()
                            let info = documentData["info"] as! [String: Any]

                            output.append(object)
                        }
                        self.performSegue(withIdentifier: "showTutors", sender: output)

                        } else {
                            self.createAlert(title: "No Tutors Found", message: "Sorry, there are no tutors for this class", buttonMsg: "Okay")
                        }
                }

            }

The exception I get from running this apparently comes from the second line db.collection(pickedClass).getDocuments, and is as follows:

*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid collection reference. Collection references must have an odd number of segments, but  has 0'

terminating with uncaught exception of type NSException

The bizarre thing is that most times this isn't an issue and the user sees the alert when the collection doesn't exist, but sometimes this happens. I never faced this issue until today, and I've been running this database and this snippet of code for over 2 months now.

Would really appreciate any help!

Upvotes: 1

Views: 1098

Answers (1)

V.Kumar
V.Kumar

Reputation: 149

  • Hi, I'm implementing FireStore in first time as I study I found this answer you can use this below mentioned code.

    Firestore.firestore().collection("YOUR_COLLECTION_NAME_HERE")
                .document("INSIDE_YOUR_COLLECTION_USE_DOCUMENT_ID_HERE_WHICH_YOU_WANT_TO_CHECK")
                .getDocument { (document, error) in
                    debugPrint(document?.exists) 
                    if document?.exists ?? false {
                        // EXIST
                    } else {
                        // NOT-EXIST
                    }
                }
    

Upvotes: 0

Related Questions