mdibound
mdibound

Reputation: 101

Dynamodb UpdateExpression: "REMOVE #items[0]" appends new list element?

I have a Dynamodb table containing a List items. I'm looking to remove an element from this list, given a specified index (using index 0 to test):

docClient.update({
    TableName: 'cart',
    Key: { 'id': id },
    ReturnValues: 'ALL_NEW',
    UpdateExpression: "REMOVE #items[0]",
    ExpressionAttributeNames : {
        "#items": "items"
    }
},  function(err, data) {   
    })

Instead of removing element 0 from the items list, it appends a new element (map) (please see attached pic of the last appended element)

...what am I doing wrong? Also, how should I be substituting a variable in place of 0, above? I tried:

...
UpdateExpression: "REMOVE #items[:index]",
ExpressionAttributeValues :
":index": index
},
...

...which results in error: Invalid UpdateExpression: Syntax error; token: \":index\", near: \"[:index]

Thank you so much!

dynamodb table

AWS-SDK: ^2.500.0

node: v10.16.0

-- EDIT: 1) AWS SDK doesn't support ExpressionAttributeValues with REMOVE, so I have to "REMOVE List[" + listNumber + "]", instead. 2) Changing UpdateExpression: "REMOVE #items[0]" to UpdateExpression: "REMOVE #i[0]" for ExpressionAttributeValues : { ":i": items } removed element 0 properly; however, DynamoDB is still appending a new list element Index : i where i was the index that I was removing.

Is this a bug?

dynamodb appending items

Upvotes: 3

Views: 2398

Answers (1)

Dev1ce
Dev1ce

Reputation: 5954

I was able to remove an element from the cart_items field as below -

table name - cart

here is my data -

{
  "id": "1",
  "cart_items": [
    "1", "2"
  ]
}

AWS CLI query to remove 1st element from the cart_items array -

aws dynamodb update-item \
    --table-name cart \
    --key '{"id":{"S":"1"}}' \
    --update-expression "REMOVE cart_items[0]" \
    --return-values ALL_NEW

Upvotes: 3

Related Questions