Firestore database, query collection and check if document exists in Python

  google-cloud-firestore, python-3.x

I have a program reading data from a Google firestore database.
The database contains info for different users, but I need to load only data for a specific user.
The data is organized in this way:

UsersInfo (Collection)
--- User01 (document)
------ UserID  (field)
------ field01 (field)
------ field02 (field)
--- User02 (document)
------ UserID  (field)
------ field01 (field)
------ field02 (field)
--- User03 (document)
------ UserID  (field)
------ field01 (field)
------ field02 (field)

each of the User documents contains an identifying ID.

I know I can find the right document in the collection by using:

user_doc_ref = db.collection(u'UsersInfo').where(u'UserID', u'==', user_ID).stream()
for x in user_doc_ref:
    user_doc = x

which is assuming there’s only one user document satisfying the query.
But this works no matter if the document actually exists or not, and always returns the generator user_doc_ref. How can I verify if this document exists? If I iterate over the generator, I can’t use it anymore afterwards.

Source: Python-3x Questions

LEAVE A COMMENT