Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible for Firestore document Snapshot data to be undefined?

Using typescript I get

QueryDocumentSnapshot<DocumentData>.data(options?: SnapshotOptions | undefined): DocumentData

The question is.. Do I really have to check if data is possibly undefined

if (snapDoc.data()) //...
else //...

or it is safe to do snapDoc.data()! for the fact that the data can never be undefined?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If it can be undefined then when or at what case does the data will return undefined?

>Solution :

If you are querying a single document using getDoc(<DoucmentReference>) that returns a DocumentSnapshot then yes, data() will return undefined if that document does not exist.

const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  // doc.data() will be undefined in this case
  console.log("No such document!");
}

If you are querying multiple documents using getDocs(<query>), a QuerySnapshot is returned that has .docs property (array of QueryDocumentSnapshot) that contains all matched documents that exist for sure. So .data() will never be undefined in that case as mentioned in the documentation.

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

If it can be undefined then when or at what case does the data will return undefined?

In short, data() can return undefined if you are using it on a DocumentSnapshot when you fetch a single document using getDoc()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading