Search code examples
node.jsamazon-dynamodbserverless-framework

How do I update a 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 update only id:2's object(name, category, price) in the List. So I wrote the handler below. And there is an error edit error ValidationException: The document path provided in the update expression is invalid for update 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: 'SET #pl[1] = :plans',
    ExpressionAttributeNames: {
      '#pl' : 'plans',
    },
    ExpressionAttributeValues: {
      ':plans': [
        {
          'name': data.planName,
          'category': data.planCategory,
          'price': data.planPrice,
        },
      ],
    },
    ReturnValues: 'UPDATED_NEW',
  }

  log.info('params', params)

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

  return success('edit plan succeeded')
}

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

{
    "plans":[
        {"planName":"ga2new",
         "planCategory": "ttnew",
         "planPrice": 5675
        }
    ]
}

Solution

  • You need to use SET.

    SET pl[1] = :plans
    

    As the docs show here:

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

    The docs for ADD say

    The ADD action supports only number and set data types.

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