【问题标题】:How to insert server timestamp in Firestore document using REST?如何使用 REST 在 Firestore 文档中插入服务器时间戳?
【发布时间】:2018-07-14 14:33:19
【问题描述】:

我想使用对Firestore createDocument 方法的REST 调用插入一个文档。其中一个字段是应在服务器上设置的时间戳字段。使用 Android SDK 就像用 @ServerTimestamp 注释 Date 字段并将其保持为空一样简单——现在我该如何在 REST 中做到这一点?

{
  "fields": {
    "timezoneId": {
      "stringValue": "Europe\/London"
    },
    "city": {
      "stringValue": "London"
    },
    "timestamp": {
      "timestampValue": "???"
    }
  }
}

我尝试使用 null0、空字符串、timestamp — 一切都失败了,并出现需要标准 RFC3339 格式的错误(例如 2018-01-31T13:50:30.325631Z)。有没有我可以使用的占位符值,或者有什么方法可以获取那个时间戳?

【问题讨论】:

  • 如果无法在 REST 调用中指明您需要服务器时间戳,您可以使用Cloud Functions Firestore onCreate 触发器,在后续更新中应用时间戳。
  • 是的,但我想也许有办法。 IIRC,使用 Firebase 实时数据库有一种方法(使用保留的字段/值)。
  • 是的,在 RTDB 中有一个特殊的令牌。也许 Firestore 有类似的东西没有记录在案,或者它可能是一个遗漏。我敢打赌 Firestore 团队的人明天会来这里。
  • 刚刚偶然发现了同样的问题,但似乎仍然没有解决方案:( iOS 和 Android SDK(仅 NODE JS)不支持每个文档的保留字段 createTime 和 updateTime 的事实使情况变得更糟。

标签: rest firebase google-cloud-firestore


【解决方案1】:

Android SDK 在创建文档时不执行createDocument 请求。相反,它使用write 请求同时发出updatetransform 请求。如果您只想使用createDocument,那么答案是否定的。

您的有效负载将如下所示:

{
  "writes": [
    {
      "update": {
        "name": "projects/{projectId}/databases/{databaseId}/documents/{document_path}",
        "fields": {
          "timezoneId": {
            "stringValue": "Europe\/London"
          },
          "city": {
            "stringValue": "London"
          }
        }
      },
      // ensure the document doesn't exist
      "currentDocument": {
        "exists": false
      }
    },
    {
      "transform": {
        "document": "projects/{projectId}/databases/{databaseId}/documents/{document_path}",
        "fieldTransforms": [
          {
            "fieldPath": "timestamp",
            "setToServerValue": "REQUEST_TIME"
          }
        ]
      }
    }
  ]
}

以这种方式添加文档的唯一缺点是您需要自己生成Document ID(SDK 会生成它们)。我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2021-04-19
    • 1970-01-01
    • 2021-12-21
    • 2018-06-10
    相关资源
    最近更新 更多