如何使用无服务器堆栈更新 dynamodb 中的嵌套列表数据?

How do I update a 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,
        }
    ]
}

现在,我只想更新列表中 id:2 的对象(名称、类别、价格)。所以我在下面写了处理程序。 CloudWatch 中出现错误 edit error ValidationException: The document path provided in the update expression is invalid for update

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

我设置了查询参数,然后像这样由邮递员测试(发送)。

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

您需要使用 SET.

SET pl[1] = :plans

如文档所示:

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

ADD 的文档说

The ADD action supports only number and set data types.

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