0

We have read a document from firebase using Python.

 doc_ref           = db.collection(u'collection_name').document(collection_abc)
        doc_fetched    = doc_ref.get()
        if (doc_fetched.exists):
            if (doc_fetched.get('doc_field')):

We get the following error

KeyError("'doc_field' is not contained in the data")

How do we check if doc_field exists in doc_fetched? This document might have some fields populated, and some not populated at the time of read (by design).

We also tried the following with the same error.

if (doc_fetched.get('doc_field') != null): 
Jack tileman
  • 813
  • 2
  • 11
  • 26

2 Answers2

1

As you can see from the API documentation for DocumentSnapshot, there is a method to_dict() that provides the contents of a document as a dictionary. You can then deal with it just like any other dictionary: Check if a given key already exists in a dictionary

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

To solve this, you can simply check the DocumentSnapshot object for nullity like this:

var doc_ref = db.collection('collection_name').doc(collection_abc);
var getDoc = doc_ref.get()
    .then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
        if(doc.get('yourPropertyName') != null) {
          console.log('Document data:', doc.data());
        } else {
          console.log('yourPropertyName does not exist!');
        }
      }
    })
    .catch(err => {
      console.log('Error getting document', err);
    });

Or you can use to_dict() method as in the @Doug Stevenson answer

Nibrass H
  • 2,403
  • 1
  • 8
  • 14
  • 2
    doc.get('yourPropertyName') returns with a KeyError since 'yourPropertyName' is not available. I had to use if ('yourPropertyName' in doc.to_dict() ). Thanks for your suggestion. – Jack tileman May 01 '20 at 15:48