Set new document in Firestore using variable as ID

66 Views Asked by At

Is there any way to create a new document in Firestore and name it after a variable?

I tried modifying the example provided here but to no avail.

This is what I attempted:

import time

#declare unix variable
unix = int(time.time())

#gcp boilerplate dictionary
data = {
'name': 'Los Angeles',
'state': 'CA',
'country': 'USA'
}

#create new doc under collection with fields form dictionary
db.collection('cities').document(unix).set(data)
1

There are 1 best solutions below

1
Frank van Puffelen On BEST ANSWER

If you pass a document ID to CollectionReference.document(), it has to be a string argument. It can be a hard-coded string, but it can also be a variable: as long as that variable is a string.

db.collection('cities').document(str(unix)).set(data)