Check if a Firestore query (whereField isEqualTo) did find no documents

Viewed 282

I want to check if my Firestore query did find any documents with the specific fields I want or not. If not I would like to proceed to some other code.

Unfortunately I haven't found a solution myself to this problem. Can you help?

Code:

Firestore.firestore().collection("conversations").whereField("mainUserID", isEqualTo: MainUID)
.whereField("otherUserID", isEqualTo: otherUserId).getDocuments { (snapshot, err) in
                
if snapshot.exists == true {                // Value of type 'QuerySnapshot?' has no member 'exists'
                        
                        
} else {
       
       }
}
1 Answers

From the docs

A FIRQueryDocumentSnapshot contains data read from a document in your Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted with the data property or by using subscript syntax to access a specific field.

A FIRQueryDocumentSnapshot offers the same API surface as a FIRDocumentSnapshot. As deleted documents are not returned from queries, its exists property will always be true and data: will never return nil.

with the important bit being this

The document is guaranteed to exist

so therefore a .exists option would not make sense due to the guaranteed existence of the snapshot.

One approach is to check how many documents are in the snapshot

if docs.count > 0 {
   //there are docs
} else {
   //there are no docs
}
Related