how to SET and DELETE using a single UpdateExpression with Dynamo

Viewed 21353

I'm trying to update an item using updateExpression, and i'd like to edit an attribute and delete another attribute on the same object, but i get the following error:

Invalid UpdateExpression: Syntax error; token: EOF near: "attributeToDelete"

I have to admit i wrote the update expression guessing the proper way to use it (failing). Here's the code snippet:

dynamodb.updateAsync({
    TableName: `myTable`,
    Key: { id: req.params.id },
    UpdateExpression: 'SET attributeToEdit = :newValue DELETE attributeToDelete',
    ExpressionAttributeValues: { ':newValue': 'valueToSet' },
  })

How am i supposed to write an UpdateExpression when I want to include more than a action? (where actions are -> SET, DELETE, REMOVE, ADD)

2 Answers

I struggled with this for a long while, so I figured a second example may be helpful for future searchers. This example is using CakePHP, Marshal JSON, SET and ADD, and includes variables to show a couple of different ways to get what you want. You'd obviously also pass in all the variables in the overall function calling this.

    $key = $this->marshaler->marshalJson('
        {
            "field_one": ' . $variableOne . '
        }
    ');

    if ($criteriaOne === null) {
        $add = $this->marshaler->marshalJson('
            {"0":{
                "field_two": ' . $variableTwo . ',
                "field_three": "' . $variableThree . '"
            }}
        ');
    } else {
        $add = $this->marshaler->marshalJson('
            {"0":{
                "field_two": ' . $variableTwo . ',
                "field_three": "' . $variableThree . '"
                "field_four": "null"
            }}
        ');
    }

    $eav = [
        ":vals" => [
            "L" => [$add[0]]
        ],
        ":vals1" => [
            "NS" => ["$variableTwo"]
        ]
    ];

    $ean = [
        "#co" => "column_one",
        "#ct" => "column_two"
    ];

    return [
        'TableName' => 'Dynamo_Table_Name',
        'Key' => $key,
        'UpdateExpression' =>
            'SET #co = list_append(:vals, #co) ADD #ct :vals1',
        'ExpressionAttributeNames' => $ean,
        'ExpressionAttributeValues' => $eav,
        'ReturnValues' => 'ALL_NEW'
    ];
Related