简体   繁体   中英

How to update existing fields of a document in Firestore with the REST API

I have a project with Cloud Firestore as database. Now I want to update the data in one document using the fetch method. My Cloud Firestore stucture is the following:

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

And I use the fetch call below:

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);
        });

Executing the fetch method I'm running in an error with message

"Invalid JSON payload received. Unknown name "active" at 'document': Cannot find field."

How can I update the existing fields of a document of Firestore with the REST API? Can anyone help me out? I've tried a lot of different "urls" and methods, but nothing works for me.

As explained in the Firestore REST API doc , You need to pass an object of type Document in the body, as follows:

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

I made the assumption that your active field is of type String (since you do "active": "false" ). If it is of type Boolean, you need to use a booleanValue property instead, as follows. See this doc for more details.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM