使用Firestore REST API更新文档字段 [英] Using the Firestore REST API to Update a Document Field

查看:44
本文介绍了使用Firestore REST API更新文档字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了很长时间,但是我不知道如何使用Firestore REST API更新文档中的字段.我查看了其他问题,但由于遇到其他错误,它们没有帮助我.

I've been searching for a pretty long time but I can't figure out how to update a field in a document using the Firestore REST API. I've looked on other questions but they haven't helped me since I'm getting a different error:

{'错误':{'代码':400,'消息':'请求包含无效的参数.','状态':'INVALID_ARGUMENT','细节':[{'@type':'类型.googleapis.com/google.rpc.BadRequest','fieldViolations':[{'field':'oil','description':扩展'fields'参数时出错.找不到路径'oil'的匹配字段."}]}]}}

{'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'oil', 'description': "Error expanding 'fields' parameter. Cannot find matching fields for path 'oil'."}]}]}}

即使我知道文档中存在石油"字段,也遇到了此错误.我是用Python编写的.

I'm getting this error even though I know that the "oil" field exists in the document. I'm writing this in Python.

我的请求正文(字段是文档中的字段,值是将该字段设置为从用户输入接收到的两个字符串的值):

My request body (field is the field in a document and value is the value to set that field to, both strings received from user input):

{
    "fields": {
        field: {
            "integerValue": value
        }
    }
}

我的请求(authorizationToken来自其他请求,dir也是来自控制目录的用户输入的字符串):

My request (authorizationToken is from a different request, dir is also a string from user input which controls the directory):

requests.patch("https://firestore.googleapis.com/v1beta1/projects/aethia-resource-management/databases/(default)/documents/" + dir + "?updateMask.fieldPaths=" + field, data = body, headers = {"Authorization": "Bearer " + authorizationToken}).json()

推荐答案

基于官方文档( 3 ), GitHub 不错的文章,对于您提供的示例,应使用以下内容:

Based on the the official docs (1,2, and 3), GitHub and a nice article, for the example you have provided you should use the following:

requests.patch(" https://firestore.googleapis.com/v1beta1/projects {projectId}/databases/{databaseId}/documents/{document_path}?updateMask.fieldPaths = field)

requests.patch("https://firestore.googleapis.com/v1beta1/projects{projectId}/databases/{databaseId}/documents/{document_path}?updateMask.fieldPaths=field")

您的请求正文应为:

{
    "fields": {
        "field": {
            "integerValue": Value
        }
    }
}

还请记住,如果要更新多个字段和值,则应分别指定每个字段和值.示例:

Also keep in mind that if you want to update multiple fields and values you should specify each one separately. Example:

https://firestore.googleapis.com/v1beta1/projects/{projectId}/databases/{databaseId}/documents/{document_path}?updateMask.fieldPaths=[Field1]&updateMask.fieldPaths=[Field2]

和请求正文将是:

{
  "fields": {
    "field": {
      "integerValue": Value
    },
    "Field2": {
      "stringValue": "Value2"
    }
  }
}

这是我测试过的一种方法,它使您可以更新文档的某些字段而不会影响其余字段.

Here is a way I have tested which allows you to update some fields of a document without affecting the rest.

此示例代码在具有4个字段的集合用户下创建了一个文档,然后尝试更新4个字段中的3个(这使未提及的字段不受影响)

This sample code creates a document under collection users with 4 fields, then tries to update 3 out of 4 fields (which leaves the one not mentioned unaffected)

from google.cloud import firestore

db = firestore.Client()

#Creating a sample new Document "aturing" under collection "users"
doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.set({
    u'first': u'Alan',
    u'middle': u'Mathison',
    u'last': u'Turing',
    u'born': 1912
})


#updating 3 out of 4 fields (so the last should remain unaffected)

doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.update({
    u'first': u'Alan',
    u'middle': u'Mathison',
    u'born': 2000
})

#printing the content of all docs under users
users_ref = db.collection(u'users')
docs = users_ref.stream()

for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))

2019年12月12日

具有REST API的补丁

我已转载了您的问题,看来您没有将请求正文正确转换为json格式.

I have reproduced your issue and it seems like you are not converting your request body to a json format properly.

您需要使用 json.dumps()将您的请求正文转换为有效的json格式.

You need to use json.dumps() to convert your request body to a valid json format.

以下是一个工作示例:

import requests
import json

endpoint = "https://firestore.googleapis.com/v1/projects/[PROJECT_ID]/databases/(default)/documents/[COLLECTION]/[DOCUMENT_ID]?currentDocument.exists=true&updateMask.fieldPaths=[FIELD_1]"

body = {
    "fields" : {
        "[FIELD_1]" : {
            "stringValue" : "random new value"
        }
    }
}

data = json.dumps(body)

headers = {"Authorization": "Bearer [AUTH_TOKEN]"}
print(requests.patch(endpoint, data=data,  headers=headers).json())

这篇关于使用Firestore REST API更新文档字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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