如何使用 REST 在 Firestore 文档中插入服务器时间戳? [英] How to insert server timestamp in Firestore document using REST?

查看:24
本文介绍了如何使用 REST 在 Firestore 文档中插入服务器时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to insert a document using a REST call to Firestore createDocument method. One of the fields is a timestamp field that should be set on the server. With Android SDK it's as simple as annotating a Date field with @ServerTimestamp and keeping it null — now how do I do it in REST?

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

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

I tried using null, 0, empty string, timestamp — everything fails with an error requiring the standard RFC3339 format (e.g. 2018-01-31T13:50:30.325631Z). Is there any placeholder value I can use, or any way to obtain that timestamp?

推荐答案

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

The Android SDK doesn't execute a createDocument request when creating the document. Instead it uses the write request to issue an update and a transform request at the same time. If you are wanting to only use createDocument, then the answer is no.

你的有效载荷看起来像这样:

Your payload would look something like this:

{
  "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 会生成它们).我希望这会有所帮助.

The only downside to adding documents this way is you would need to generate the Document ID yourself (the SDK's generate them). I hope this helps.

这篇关于如何使用 REST 在 Firestore 文档中插入服务器时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆