Firestore Update a document field Using Rest API

有些话、适合烂在心里 提交于 2020-04-10 08:59:49

问题


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.



来源:https://stackoverflow.com/questions/49447897/firestore-update-a-document-field-using-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!