【问题标题】:Set new document in Firestore using variable as ID使用变量作为 ID 在 Firestore 中设置新文档
【发布时间】:2021-04-04 19:30:24
【问题描述】:

有什么方法可以在 Firestore 中创建一个新文档并以变量命名?

我尝试修改here提供的示例,但无济于事。

这是我尝试的:

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)

【问题讨论】:

  • 你分享的代码有什么问题?
  • 当我尝试以我的“unix”变量命名时,没有创建新文档。似乎文档名称只能硬编码。

标签: python google-cloud-firestore


【解决方案1】:

如果您将文档 ID 传递给 CollectionReference.document(),则它必须是字符串参数。它可以是硬编码的字符串,但也可以是变量:只要该变量是字符串即可。

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

【讨论】:

  • 我完全忽略了这一点,感谢您指出这一点,非常感谢。
猜你喜欢
  • 2020-10-16
  • 1970-01-01
  • 2020-05-09
  • 2020-05-06
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多