Python 2.7 Firebase python-如何检查文档中是否存在字段(属性)
我们已经使用Python阅读了firebase的一个文档Python 2.7 Firebase python-如何检查文档中是否存在字段(属性),python-2.7,google-cloud-firestore,Python 2.7,Google Cloud Firestore,我们已经使用Python阅读了firebase的一个文档 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')): 我们得到以下错误 KeyError("'d
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')):
我们得到以下错误
KeyError("'doc_field' is not contained in the data")
如何检查提取的单据中是否存在单据字段?此文档可能有一些字段已填充,有些字段在读取时未填充(按设计)
我们也尝试了以下同样的错误
if (doc_fetched.get('doc_field') != null):
从的API文档中可以看到,有一种方法将文档的内容作为字典提供。然后,您可以像处理任何其他字典一样处理它:从的API文档中可以看到,有一种方法将文档的内容作为字典提供。然后,您可以像处理任何其他字典一样处理它:要解决此问题,您只需检查
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);
});
或者您可以使用中的方法来解决此问题,只需检查
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);
});
或者您也可以使用doc.get中的方法。由于“yourPropertyName”不可用,因此(“yourPropertyName”)返回一个键错误。我必须使用if('yourPropertyName'在doc.to_dict()中)。感谢您的建议。doc.get('yourPropertyName')返回一个键错误,因为'yourPropertyName'不可用。我必须使用if('yourPropertyName'在doc.to_dict()中)。谢谢你的建议。