EDIT: Problem Found, see my next comment !
Collection.on_snapshot works only on top-level collections.
Calling on_snapshot on any sub-collection does nothing. It will be called once, where
first two arguments will be empty arrays, and last one will be correct timestamp, no matter what is actually inside of the collection. It will never be called again.
Someone already found this issue on the Stack Overflow:
https://stackoverflow.com/questions/54407320/firestore-listen-to-documents-in-a-subcollection
But no response given, nor any similiar issue opened.
Fedora 29, Linux 4.20.14.-200.fc29.x86_64
Python 3.6.8 (virtualenv)
google-api-core==1.8.1
google-auth==1.6.3
google-cloud-core==0.29.1
google-cloud-firestore==0.31.0
google-cloud-storage==1.14.0
google-resumable-media==0.3.2
db = firestore.Client()
def on_snapshot(snapshot, changes, ts):
for doc in snapshot:
print(doc)
# This would work as expected
db.collection("users").on_snapshot(on_snapshot)
# These will do nothing
db.collection("users/USER/values").on_snapshot(on_snapshot)
db.collection("users", "USER", "values").on_snapshot(on_snapshot)
db.collection("users").document("USER").collection("values").on_snapshot(on_snapshot)
As pointed out, I am rewriting Node.js and similar code does indeed work in Node, but not in the Python version
Ok fast update:
Found out the problem:
https://github.com/googleapis/google-cloud-python/blob/f242cc1a72818d4dc25927d962ec309ff5c5f3c2/firestore/google/cloud/firestore_v1beta1/watch.py#L354
query._client._database_string will always returns a root of database, instead of parent document of the collection.
Quicklu digging up in the guts of the Query class, found out that it is actually easy to get a real parent path in the _parent_info(), and this makes on_snapshot to work as expected:
(parent, _) = query._parent._parent_info()
query_target = firestore_pb2.Target.QueryTarget(
parent=parent, structured_query=query._to_protobuf()
)
Sorry, but I actually doesn't have time to create patch or PR.Please update manually if possible.
Although this issue is closed, I'm still facing the same problem as the one described by @Kyras. I'm currently using: