Bram-N
Bram-N

Reputation: 426

Firestore getDocument always returns document even if non existant, docs incomplete?

I've started working with Firestore and stumbled upon a problem.

The code from the Firestore docs to retrieve a document is:

let docRef = db.collection("cities").document("SF")

docRef.getDocument { (document, error) in
    if let document = document {
        print("Document data: \(document.data())")
    } else {
        print("Document does not exist")
    }
}

However, if I don't have a document with that id, the "let document = document" will always go through and it will try to print the document data, which does not exist, resulting in an error.

Now, this is easily solvable by changing the if to:

if let document = document, document.exists {
   ...
}

Shouldn't this be documented as well? Or am I overlooking something?

Edit: Link to docs

Upvotes: 2

Views: 642

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38319

I can't offer an authoritative answer, but based on my experience, the examples for Swift and Android in the documentation you linked are wrong. The returned document snapshot is never null and one should always test exists.

Upvotes: 1

Related Questions