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

查看:32
本文介绍了使用 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:

{'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': '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'."}]}]}}

即使我知道文档中存在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()

推荐答案

基于官方文档 (1,23)、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.

此示例代码在集合 users 下创建一个包含 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()))

10/12/2019

使用 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天全站免登陆