【问题标题】:Firestore create document with fields at root with REST APIFirestore 使用 REST API 在根目录创建文档
【发布时间】:2021-10-15 01:12:44
【问题描述】:

我正在尝试进行 API 调用以在我的“用户”集合中创建一个文档,并包含“年龄”和“姓名”作为字段。不幸的是,当我调用 API 时,我创建了 Users>document>collection>document>info,我想省略:Users>document>collection>document>info 但 API 不允许。 请参考下图。

目前我的代码如下所示:

POST https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users/hello/APITest HTTP/1.1

Accept: application/json
Content-Type: application/json

{
  "fields": {
    "Name": {
      "stringValue": "Josh"
    },
    "Age": {
      "integerValue": "23"
    }
  }
}

我删除了一些部分。

关于如何进行这项工作的任何建议?

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    查看您当前的目标网址:

    https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users/hello/APITest
    

    您正在尝试将数据写入/Users/hello/APITest,这是集合的路径,而不是文档。由于您尚未提供文档 ID,Firestore 会为您生成一个并在该集合中创建一个新文档:

    /Users/hello/APITest/{automaticDocumentId}
    

    为防止出现这种情况,您需要将路径更改为文档的路径,例如 /Users/hello,这会使您的目标 URL:

    https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users/hello
    

    或者,您可以让 Firestore 仅使用 /Users 和目标 URL 为您生成一个 ID:

    https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users
    

    【讨论】:

      【解决方案2】:

      http POST 请求路径由两个必需的路径参数组成,一个是parent,另一个是collectionId。在您的情况下,http POST 请求使用第二类parent 路径参数,该参数在父路径参数hereOR 部分中提到,即

      projects/{project_id}/databases/{databaseId}/documents/chatrooms/{chatroom_id}.
      

      因此,在您的情况下,parent 路径参数是:projects/###/databases/(default)/documents/Users/helloAPITestcollectionId。因此,Firestore 正在创建一个嵌套集合,即集合 Users,其中包含一个文档 hello,另一个集合 APITest 以及其中一个具有自动生成文档 ID 的文档。

      因此,要在根文档中包含字段值,您必须将parent 路径参数指定为:projects/{project_id}/databases/{databaseId}/documents,并将collectionId 路径参数指定为Users。它将使用 collectionId Users 创建一个集合,并在其中创建一个具有自动生成的文档 ID 的文档。

      因此,在您的情况下,http post 请求将如下所示 -

      https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users
      

      请注意,如果您尝试使用https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users/hello,它将引发无效参数错误,因为此处提到的路径参数不符合上述文档中提到的 Firestore http POST 请求路径参数要求。

      如果您想使用自定义文档 ID,则可以使用 here 中提到的查询参数。因此,您的 http 请求将如下所示 -

      https://firestore.googleapis.com/v1/projects/###/databases/(default)/documents/Users/?documentId=custom_document_id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-17
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 2022-11-30
        • 2018-04-12
        相关资源
        最近更新 更多