Firebase Firestore: get generated ID of document (Python)
Documentation is very limited on this, but I managed to figure it out through trial and error.
If you want to use add
method as the question indicates, instead of a document reference together with a set
method, try:
my_data = {"key": "value"}
response = db.collection(u'campaigns').add(my_data)
id = response[1].id
data = response[1].get().to_dict()
Firestore response when using add
method contains a tuple:
DatetimeWithNanoseconds
object - contains the time the document was created- Firestore document reference that contains
id
and a document snapshot, from which you can extract the document data by chainingget()
andto_dict()
.
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)
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