Carlo
Carlo

Reputation: 1578

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

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.

EDIT: I found a way to get around it, by using:

current_user_doc = None
current_user_document_ref = db.collection(u'UsersInfo').where(u'UserID', u'==', user_ID).stream()
for dummy in current_user_document_ref:
    current_user_document = dummy.id
if current_user_document is not None:
    print(f"\tUser found in remote document {current_user_document}")
    doc_ref = db.collection(u'UsersInfo').document(current_user_document).collection(u'whatever').stream()

so, I'm iterating over the generator, but saving the document if it exists, so I can use it later on. I was wondering if there's a more direct and pythonic way.

Upvotes: 1

Views: 1340

Answers (1)

Peter Obiechina
Peter Obiechina

Reputation: 2835

Try this (sorry my python is not perfect):

user_doc_ref = db.collection(u'UsersInfo').where(u'UserID', u'==', user_ID).stream()
documents = [d for d in user_doc_ref]

if len(documents):
    for document in documents:
        print(u'Not empty')
else:
    print(u'empty query')

A better way to structure your data would be to make the document id the userId

Your data structure would look like:

UsersInfo (Collection)
--- UserID (for User01) (document)
------ field01 (field)
------ field02 (field)

and then you fetch the data like this

doc_ref = db.collection(u'UsersInfo').document(user_ID)

doc = doc_ref.get()
if doc.exists:
    print(f'Document data: {doc.to_dict()}')
else:
    print(u'No such document!')

Upvotes: 1

Related Questions