Skip to content
Advertisement

Firestore – Why check if DocumentSnapshot is not null AND call exists?

Take a look at this code example from the Firestore documentation:

JavaScript

https://firebase.google.com/docs/firestore/query-data/get-data

Why check if document != null? If I read the source code correctly (beginner), the exists method checks for nullity internally.

Advertisement

Answer

A successfully completed task will never pass null for the DocumentSnapshot. If the requested document does not exist, you’ll get an empty snapshot. This means that:

  • Calling document.exists() returns false
  • Calling document.getData() throws an exception

So there is indeed no reason to check if document != null before calling document.exists().

Advertisement