Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

updateItem/putItem object into array in dynamodb

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading