Firestore Update a document field Using Rest API

2020-08-25 05:28发布

问题:

Im trying to perform PATCH Opeartion in cloud firestore using REST API.

This is my Request body

`{
  "fields": {
    "name": {
      "stringValue":"Dinesh"
    }
  }
}`

When i fire the request , All the existing fields inside the document are getting deleted and only the name field is getting updated. In the Documentation they have given the Document Mask Document Mask. but i dont understand how it works , neither im able to find any samples for that. Somebody know how to update only one field inside the document without affecting other fields ?

回答1:

Without a DocumentMask object, the patch method defaults to replacing the Firestore Document with the request body rather than updating the submitted fields and retaining omitted fields.

The DocumentMask is submitted as an updateMask parameter containing the fieldPaths to be patched. It took a while but thanks to this answer and a lot of attempts I figured out that each fieldPath property of the updateMask object needs to be individually included in the query string of the request url:

https://firestore.googleapis.com/v1beta1/projects/{projectId}/databases/{databaseId}/documents/{document_path}?updateMask.fieldPaths=status&updateMask.fieldPaths=title

Where status and title are two fields in the request body. Note that fields included in the request body are disregarded if they are omitted from the query string, remaining unchanged.



回答2:

Your request body is ok. But you need to use the update mask.

From reading the documents I found that the DocumentMask is used to restrict a get or update operation on a document to a subset of its fields. So by adding 'name' to your field paths on the mask, it will only allow you to update that specific field and the others won't get deleted.

You can read more about it here.