【问题标题】:Problem deleting an element in the DynamoDB table with secondary index使用二级索引删除 DynamoDB 表中的元素时出现问题
【发布时间】:2022-01-31 01:45:53
【问题描述】:

我卡住了,因为我在删除 DynamoDB 表中具有主键和全局二级索引的元素时遇到问题(没有排序键)。

我收到以下错误: “提供的关键元素与架构不匹配”

我很绝望,我也试图查看这个网站上其他帖子的答案,但我找不到任何关于删除的信息。

这是我的代码:

const AWS = require("aws-sdk");

const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
  let body;
  let statusCode = 200;
  const headers = {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "DELETE",
  };

  try {
    switch (event.routeKey) {
      case "DELETE /fragments/{id}":
        await dynamo
          .delete({
            TableName: "fragment",
            Key: {
              id: event.pathParameters.id
            }
          })
          .promise();
        body = `Deleted fragment ${event.pathParameters.id}`;
        break;
       default:
        throw new Error(`Unsupported route: "${event.routeKey}"`);
    }
  } catch (err) {
    statusCode = 400;
    body = err.message;
  } finally {
    body = JSON.stringify(body);
  }

  return {
    statusCode,
    body,
    headers
  };
};

【问题讨论】:

  • 分区键是“id”?
  • @hunterhacker 没错
  • id 键的 DynamoDB 数据类型是 String 还是 Number(或 Binary)?密钥的类型是否与typeof event.pathParameters.id一致?
  • @fedonev id的数据类型为number。与typeof一致event.pathParameters.id
  • @fedonev 因为这个原因我被困住了。二级索引会不会是问题所在?

标签: node.js amazon-web-services amazon-dynamodb


【解决方案1】:

TL;DRevent.pathParameters.idstring 转换为number 类型。

// convert id from string to number
Key: { id: parseInt(event.pathParameters.id, 10) }

DynamoDB.DocumentClient infers the key schema types 来自 Key 中的 javascipt 类型。 event.pathParameters.id 是一个字符串,但您的键架构需要一个数字,因此 DynamoDB 返回架构不匹配错误。

我们怎么知道event.pathParameters.idstringlambda typings for API Gateway events 告诉我们:

// APIG event pathParameters
export interface APIGatewayProxyEventPathParameters {
    [name: string]: string | undefined;
}

【讨论】:

  • 完美,无限感谢。经过几天的“战斗”,这就是问题
猜你喜欢
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
相关资源
最近更新 更多