Search code examples
node.jsamazon-dynamodbserverless-framework

How do I add nested list data in dynamodb using serverless stack?


I have a dynamoDB table that has an Item that includes a user and a List of plans. It looks like this:

Item: 
{
    user: 'abc123',
    plans: [
        {
            id: 1,
            name: 'movies',
            category: 'category',
            price: 200,
        },
        {
            id: 2,
            name: 'fishing',
            category: 'category2',
            price: 400,
        }
    ]
}

Now, I want to add another plan. So I wrote the handler below. And there is an error add error ValidationException: Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: :price in CloudWatch.

export const processAddPlan = async (event:APIGatewayEvent) => {

  const data = JSON.parse(event.body)
  const { store, id } = event.queryStringParameters
  
  const params = {
    TableName: usersTable,
    Key: {
      store: store,
      id: id,
    },
    UpdateExpression: 'ADD #pl :plans, id :id, name :name, category :category, price :price',
    ExpressionAttributeNames: {
      '#pl' : 'plans',
    },
    ExpressionAttributeValues: {
      ':plans': [
        {
          ':id': uuid.v4(),
          ':name': data.planName,
          ':category': data.planCategory,
          ':price': data.planPrice,
        },
      ],
    },
    ReturnValues: 'ALL_NEW',
  }

  log.info('params', params)

  await dynamoDb.update(params).catch(e => log.info('add error', e))

  return success('add plan succeeded')
}

I set query params and I tested(send) by postman like this.

{
    "plans":[
        {"planName":"ga",
         "planCategory": "tt",
         "planPrice": 567
        }
    ]
}

I referred "Adding Elements to a Set".https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html enter image description here


Solution

  • Just provide one value. Something like this (untested code):

     const params = {
        TableName: usersTable,
        Key: {
          store: store,
          id: id,
        },
        UpdateExpression: 'ADD #pl :plans',
        ExpressionAttributeNames: {
          '#pl' : 'plans',
        },
        ExpressionAttributeValues: {
          ':plans': [
            {
              'id': uuid.v4(),
              'name': data.planName,
              'category': data.planCategory,
              'price': data.planPrice,
            }
          ]
        },