如何使用无服务器堆栈在 dynamodb 中添加嵌套列表数据?

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

我有一个 dynamoDB table,它有一个包含用户和计划列表的项目。它看起来像这样:

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

现在,我想添加另一个计划。所以我在下面写了处理程序。 CloudWatch 中出现错误 add error ValidationException: Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: :price

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')
}

我设置了查询参数,并像这样通过邮递员进行了测试(发送)。

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

我提到了“将元素添加到集合”。https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html

只需提供一个值。像这样(未经测试的代码):

 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,
        }
      ]
    },

这如我所愿。谢谢!

UpdateExpression: 'SET #pl = list_append(#pl, :plans)',
    ExpressionAttributeNames: {
      '#pl' : 'plans',
    },
    ExpressionAttributeValues: {
      ':plans': [
        {
          'id': uuid.v4(),
          'name': data.planName,
          'category': data.planCategory,
          'price': data.planPrice,
        },
      ],
    },
    ReturnValues: 'ALL_NEW',
  }