Search code examples
firebaserestgoogle-cloud-firestore

How use arrayUnion using firestore rest api?


I can't find a way to achieve the request even following the Firestore documentation.

I tried this request:

PATH (PATCH METHOD): https://firestore.googleapis.com/v1/projects/social-autt/databases/(default)/documents/error/AA/

BODY:

{
    "updateTransforms": [
        {
            "fieldPath": "kaja",
            "appendMissingElements": {
                "values": [
                    {
                        "stringValue": "Aasd"
                    }
                ]
            }
        }
    ]
}

RESPONSE:

{
    "error": {
        "code": 400,
        "message": "Invalid JSON payload received. Unknown name \"updateTransforms\" at 'document': Cannot find field.",
        "status": "INVALID_ARGUMENT",
        "details": [
            {
                "@type": "type.googleapis.com/google.rpc.BadRequest",
                "fieldViolations": [
                    {
                        "field": "document",
                        "description": "Invalid JSON payload received. Unknown name \"updateTransforms\" at 'document': Cannot find field."
                    }
                ]
            }
        ]
    }
}

Solution

  • Based on the answer to How do I add/delete array elements on a Firestore document via REST? and the documentation for documents:commit, Write, DocumentTransform, and FieldTransform, I was able to execute this array union in Postman:

    enter image description here

    The JSON of the request:

    {
        "writes": [{
          "transform": {
            "document": "projects/projectID.../databases/(default)/documents/79447051/test",
            "fieldTransforms": [
                { "fieldPath": "array",
                  "appendMissingElements": {
                    "values": [
                      { "stringValue": "third" }
                    ]
                  }
                }
              ]
            }
        }]
    }
    

    In this:

    • the blurred out bit is my project ID
    • the 79447051 is the collection ID (and your question ID here)
    • test is my document ID
    • array is the name of the array field that we're updating
    • third is the value we're adding to the array (if it's not already in there)

    The response I got back from Firestore:

    {
        "writeResults": [
            {
                "updateTime": "2025-02-18T21:06:02.185573Z",
                "transformResults": [
                    {
                        "nullValue": null
                    }
                ]
            }
        ],
        "commitTime": "2025-02-18T21:06:02.185573Z"
    }