【发布时间】:2020-02-20 15:54:49
【问题描述】:
我有一个名为Inbox 的集合,其中包含多个文档。我正在尝试在其中一个inbox_documents 的新firestore 子集合中创建一个新文档。新文档应该有一个自定义 ID,这里称为 folder_id。我的代码如下:
# Get the correct inbox document reference.
inbox_ref = fs_client.collection(u'inbox').document(self.inbox_id)
if not inbox_ref.get().exists:
raise ValueError("Referenced inbox does not exist.")
# Make a new document in the model collection and update it
# with the provided folder dictionary.
doc = inbox_ref.collection(u'folder').document(folder_id)
doc.set(folder_dict)
现在根据here 找到的文档,我可以简单地将数据分配给集合中的文档。如果(子)集合不存在,Firestore 应该会自动为我创建它。 在this 页面上,我发现了一个代码 sn-p 正是我想要完成的。
使用 set() 创建文档时,必须指定要创建的文档的 ID。例如:
db.collection(u'cities').document(u'new-city-id').set(data)
它与我的代码几乎相同。但是由于某种原因,当我尝试运行我的代码时,我得到以下 ValueError: A document must have an even number of path elements. 我在网上搜索了这个错误,发现当提供的路径长度错误时会出现这个错误。但我的路径似乎是正确的。
当我没有为文档提供自定义 ID 而是让 Firestore 使用以下代码自动创建它时,代码确实可以工作,但显然使用自动生成的 ID 而不是我需要的自定义 ID。
doc = inbox_ref.collection(u'folder').document()
doc.set(folder_dict)
我也尝试使用create() 而不是set(),但没有运气。
我正在使用 google-cloud-firestore python 包,版本 1.6.2。
关于我下一步可以尝试什么或我在这里做错了什么有什么建议吗?
【问题讨论】:
标签: python-3.x google-cloud-firestore