pythonfirebasegoogle-cloud-platformgoogle-cloud-firestore

Firebase Firestore: get generated ID of document (Python)


I can create a new document (with auto generated ID), and store a reference to it like this:

my_data = {"key": "value"}
doc_ref = db.collection(u'campaigns').add(my_data)

I can access the data itself like:

print (doc_ref[0]) # prints {"key": "value"}

But when I try to access the doc_ref ID, I am unable to:

# All of these throw attribute errors
doc_ref.get()
doc_ref.data()
doc_ref.id

There are other posts which suggest how to do this in Javascript, but none which work for the Python SDK!

How can I access the generated ID of a document I created?


Solution

  • The documentation is unclear, but I finally got it to work:

    doc_ref = db.collection(u'campaigns').document()
    doc_ref.set(my_data)
    print(doc_ref.id)