Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
David Ferris Avatar asked Jul 04 '19 17:07

David Ferris


People also ask

How do I find my generated document ID in firestore?

Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.

How do I list all Subcollections of a cloud firestore document?

Just enter a document path in the dedicated field and click the button “Get Subcollections”: If the document has one or more subcollections the page will display their id(s). If the document at the path does not exist or if it does not have any subcollection, the Cloud Function will return an empty array.


2 Answers

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)
like image 113
David Ferris Avatar answered Sep 20 '22 18:09

David Ferris


To get ID after save on Python:

This will return for instance some id like wlJQKyVDsIIpX0x3NBmt

doc_ref = db.collection('promotions').add(data)
return doc_ref[1].id
like image 44
LinuxFelipe-COL Avatar answered Sep 21 '22 18:09

LinuxFelipe-COL