【问题标题】:How to update existing fields of a document in Firestore with the REST API如何使用 REST API 更新 Firestore 中文档的现有字段
【发布时间】:2020-11-26 17:49:57
【问题描述】:

我有一个使用 Cloud Firestore 作为数据库的项目。现在我想使用 fetch 方法更新一个文档中的数据。我的 Cloud Firestore 结构如下:

Logging (Collection)
   [userID] (Document)
       Notifications (Collection)
          [notificationID] (Document)
              active: "true"
              type: "T1"

我使用下面的 fetch 调用:

fetch("https://firestore.googleapis.com/v1/projects/[ID]/databases/(default)/documents/Logging/[userID]
       +"/Notifications/[notificationID]?updateMask.fieldPaths=active", {
          method: 'PATCH', 
          body: JSON.stringify({
            "active": "false"
          }),
          headers: {
            Authorization: 'Bearer ' + idToken,
            'Content-Type': 'application/json'
          }
        }).then( function(response){
          console.log(response);
          response.json().then(function(data){
            console.log(data);
          });
        }).catch(error => {
          console.log(error);
        });

执行我正在运行的 fetch 方法时出现错误消息

“收到无效的 JSON 有效负载。‘文档’处的未知名称“活动”:找不到字段。”

如何使用 REST API 更新 Firestore 文档的现有字段?谁能帮我吗?我尝试了很多不同的“url”和方法,但对我没有任何作用。

【问题讨论】:

    标签: javascript json firebase rest google-cloud-firestore


    【解决方案1】:

    如 Firestore REST API doc 中所述,您需要在正文中传递 Document 类型的对象,如下所示:

        {
          method: 'PATCH',
          body: JSON.stringify({
            fields: {
              active: {
                stringValue: 'false',
              },
            },
          }),
        }
    

    我假设您的 active 字段是字符串类型(因为您是 "active": "false")。如果它是布尔类型,则需要改用booleanValue 属性,如下所示。有关详细信息,请参阅此doc

        {
          method: 'PATCH',
          body: JSON.stringify({
            fields: {
              active: {
                booleanValue: false,
              },
            },
          }),
        }
    

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      相关资源
      最近更新 更多