Firebase Python-如何检查文档中是否存在字段(属性)

时间:2020-04-29 18:57:09

标签: python-2.7 google-cloud-firestore

我们已经使用Python从firebase中阅读了一个文档。

@Input

我们收到以下错误

 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')):

我们如何检查doc_fetched中是否存在doc_field?该文档可能填充了某些字段,而在阅读时(设计使然)则未填充某些字段。

我们还尝试了以下相同的错误。

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

2 个答案:

答案 0 :(得分:1)

DocumentSnapshot的API文档中可以看到,有一种方法to_dict()将文档的内容作为字典提供。然后,您可以像处理其他任何词典一样处理它:Check if a given key already exists in a dictionary

答案 1 :(得分:1)

要解决此问题,您可以像下面这样简单地检查DocumentSnapshot对象是否为空:

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);
    });

或者您可以像to_dict()一样使用@Doug Stevenson answer方法