Home > Net >  updateItem/putItem object into array in dynamodb
updateItem/putItem object into array in dynamodb

Time:12-31

I'm having trouble pushing an object into an array/Set the object into it as docs state in dynamodb. Getting the error:

Invalid UpdateExpression: Incorrect number of operands for operator or function; operator or function: if_not_exists, number of operands: 1

What am I doing wrong? I appreciate any help!

   export async function postTrade(position) {
    let params = {
        Key: {
            PK: 'stocks' 
        },
        UpdateExpression: 'set #tickers = list_append(if_not_exists(#tickers))',
        ExpressionAttributeNames: {
            '#tickers': 'tickers'
        },
        ExpressionAttributeValues: {
            ':tickers': [position]
        },
        TableName: 'stockTable'
    };
    await docClient.update(params).promise();
}

Dynamo record

{
 "PK": "stocks",
 "tickers": [
 ]
}

CodePudding user response:

Appending to a list

list_append takes 2 parameters, not one:

  • list_append (list1, list2)

  • The function takes two lists as input and appends all elements from list2 to list1

Checking an attribute exists

Likewise, if_not_exists() takes 2 parameters:

  • if_not_exists (path, value)

  • If the item does not contain an attribute at the specified path, if_not_exists evaluates to value; otherwise, it evaluates to path. Therefore, you should use an empty array as a parameter.

Solution

Pass 2 parmeters to each function, which should allow you to append to a list.

    let params = {
        Key: {
            PK: 'stocks' 
        },
        UpdateExpression: 'set #tickers = list_append(if_not_exists(#tickers, :empty_list), :tickers)',
        ExpressionAttributeNames: {
            '#tickers': 'tickers'
        },
        ExpressionAttributeValues: {
            ':tickers': [position],
            ':empty_list': []
        },
        TableName: 'stockTable'
    };
  • Related