Angel Chen
Angel Chen

Reputation: 67

'DocumentReference' object has no attribute 'to_dict'

I'm using python3 to query a database on firestore. My code is the following:

def getWebConsultReData():
    collection = db.collection("webconsult_threescrap").where("compositeKey", "==", "10004-5327729026")
    docs = [snapshot.reference for snapshot in collection.stream()]
    mDictList = []
    print(docs)
    for doc in docs:   
        formattedData = doc.to_dict()
getWebConsultReData()

However, I got the following error:

[<google.cloud.firestore_v1.document.DocumentReference object at 0x7f2a183413c8>]
Traceback (most recent call last):

  File "<ipython-input-42-172d5765da1d>", line 9, in <module>
    getWebConsultReData()

  File "<ipython-input-42-172d5765da1d>", line 7, in getWebConsultReData
    formattedData = doc.to_dict()

AttributeError: 'DocumentReference' object has no attribute 'to_dict'

What I'm sure are: The filter is valid, in fact, the following snapshot shows the exact syntax with GUI enter image description here

Also the document exists. Can anybody help me out? Thank you very much!

Upvotes: 1

Views: 6087

Answers (2)

jkr
jkr

Reputation: 660

from google.cloud import firestore

def tableconversations(userdata):
  docarray = []
  db = firestore.Client()
  collection = db.collection('tableQuestions').where('userID', '==', userdata['ID']).get()
  print("user history matched records",collection)
  for doc in collection:
     print(doc.to_dict())
     docarray.append(doc.to_dict())
  return docarray

Upvotes: 0

robsiemb
robsiemb

Reputation: 6354

Your problem is that at the point of the error, docs is an array of DocumentReferences and not an array of DocumentSnapshots because you remove all the other data a few lines up. DocumentReference only gives a path to the document, it does not contain the entirety of the document's data.

To do something equivalent (gather an array of DocumentReferences but also have some access to the actual documents), you'd need to do something like this:

def getWebConsultReData():
    collection = db.collection("webconsult_threescrap").where("compositeKey", "==", "10004-5327729026")
    docs = []
    for doc in collection.stream():   
        formattedData = doc.to_dict()
        print(formattedData)
        docs.append(doc.reference)
    print(docs)
getWebConsultReData()

If it helps, you can also review the example in the documentation of how to get multiple documents from a collection.

Upvotes: 5

Related Questions