thinkmore
thinkmore

Reputation: 239

How to fix Firestore query suddenly not working

I'm developing google cloud api function and the following query did work(means get the data) when I made first. query = db.collection(collectionId).where('dataSchema', '==', 'messages').order_by('dataSourceModifyDate', direction=firestore.Query.DESCENDING).limit(1)

But I was developing other query and re-run the query, but it didn't work(means didn't get any data) although that query works in the google cloud platform.

query = db.collection(collectionId).where('dataSchema', '==', 'messages').order_by('dataSourceModifyDate', direction=firestore.Query.DESCENDING).limit(1)
     docs = query.get()
     temp = datetime.datetime.strptime('1900-01-01T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ')
     if len(list(docs)) != 0:
         recent_doc = list(docs)[0]
                temp = datetimewithnanoToDatetime(recent_doc.to_dict()['dataSourceModifyDate'])

If run code, the following error occurs.

File "D:\work\upwork\simon_chapleau\projects\krakenGetEntitiesFrom365.py", line 210, in index
return getEntitiesFrom365(request)
File "D:\work\upwork\simon_chapleau\projects\krakenGetEntitiesFrom365.py", line 97, in getEntitiesFrom365
recent_doc = list(docs)[0]
IndexError: list index out of range

Upvotes: 0

Views: 244

Answers (1)

vitooh
vitooh

Reputation: 4262

This is because get is returning iterator, and you are calling the iterator (docs) twice. I am not sure how to explain it fast so look at this console screenshot:

enter image description here

First part I call iterator len it has value, but next time it does not.

So when you check it in if len(list(docs)) != 0: you get value and next time you call the same - it do not have. I think the solution will be to create the list and work with it (like in list_it2 in the example).

Upvotes: 1

Related Questions