How to catch empty QuerySnapShot with Firestore python API?

Viewed 535

Context

I would like to fetch some data from Firestore that way:

query = db.collection("users").where("age", ">", 20)

for document in query.stream():
    print("User id: {}".format(document.id))

However, I cannot assert whether it will iterate over documents. Indeed, if no documents match with my where condition, nothing happens. I would like to raise an Exception instead.

Question

How can we catch any empty QuerySnapshot with the python API ?

Resources: Firebase documentation

2 Answers

I solve in this way:

documents = [d for d in db.collection("users").where("age", ">", 20).stream()]

if len(documents):
    for document in documents:
        print("User id: {}".format(document.id))
else:
    print('empty query') 
db.collection("users").where("age", ">", 20)

returns null if no document match with your where, please check for

if query!= null : for document in querenter code herey.stream(): print("User id: {}".format(document.id))

Related