2

Using serverless-stack.

I have a table company with multiple branches:

     new sst.Table(this, 'Company', {
        fields: {
            userId: sst.TableFieldType.STRING,
            companyId: sst.TableFieldType.STRING,
            companyName: sst.TableFieldType.STRING,
            branches: [
                {
                    branchId: sst.TableFieldType.STRING,
                    branchName: sst.TableFieldType.STRING
                }
            ]
        },
        primaryIndex: {partitionKey: "userId", sortKey: "companyId"}
    })

I am trying to add branch to the branches:

const branch = {
    branchId: uuid.v1(),
    branchName: data.branchName
}
const params = {
    TableName: process.env.COMPANY_TABLE_NAME,
    Key: {userId: "1", companyId: data.companyId},
    UpdateExpression: "ADD #branches :branch",
    ExpressionAttributeNames: { "#branches" : "branches" },
    ExpressionAttributeValues: { ":branch": [branch] }
 }

But I get this error:

ERROR ValidationException: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: LIST, typeSet: ALLOWED_FOR_ADD_OPERAND
 ValidationException: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: LIST, typeSet: ALLOWED_FOR_ADD_OPERAND
Alvin
  • 8,219
  • 25
  • 96
  • 177

2 Answers2

0

ADD is only for numbers and sets. Your branches attribute is a list. So you can use SET with list_append.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET.UpdatingListElements

hunterhacker
  • 6,378
  • 1
  • 14
  • 11
  • I did try using set with list_append UpdateExpression: "SET #branches = list_append(#branches, :branch)",, but getting ERROR ValidationException: An operand in the update expression has an incorrect data type ValidationException: An operand in the update expression has an incorrect data type – Alvin Jan 17 '22 at 01:38
  • So now you’re on the right track but there’s just a detail wrong. The docs have code that works. Attach a fully runnable but failing script if you can’t figure out the broken detail. – hunterhacker Jan 17 '22 at 17:13
0

SET #branches = list_append(#branches, :branch) is correct. But ExpressionAttributeValues should be ExpressionAttributeValues: { ":branch": {"L":[branch]}}
You can refer to https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.update_item

Nick
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 17 '22 at 08:46