You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Lambda+AWS SDK向DynamoDB插入数据时遇属性类型不匹配错误

问题

我有一个Lambda函数,尝试向DynamoDB表插入数据。表的主键(PK)title_hash类型是字符串,但插入时收到错误:One or more parameter values were invalid: Type mismatch for key title_hash expected: S actual: M——明明传入的是字符串,却被识别成Map类型。

我的代码如下:

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");

const {
    DynamoDBDocumentClient,
    PutCommand,
} = require("@aws-sdk/lib-dynamodb")

const client = DynamoDBDocumentClient.from(
    new DynamoDBClient({})
);

const putItemCommandInput = {
    TableName: process.env.TABLE_NAME,
};

// 以下代码在函数handler中
putItemCommandInput.Item = {
    title_hash: { "S": strip(event.title)}, // pk
    album_title: { "S": event.album_title }, // sk
    number: { "N": event.number },
    title: { "S":  event.title },
    length: { "N": event.length },
    artist_name: { "S":  event.artist_name },
    cover_url: { "S":  event.cover_url},
    plays_total: { "N": "0" },
};

console.log('Storing new song');
console.log(putItemCommandInput.Item);

const PutItemCommand = new PutCommand(putItemCommandInput);

const body = await client.send(PutItemCommand);


// 清理字符串的函数,确实返回字符串
function strip(inputString) {
    return inputString.replace(/[^a-z0-9]/gi, '').toLowerCase();
}

执行日志:

2024-04-26T10:40:02.070Z    81327c7f-65bd-4af6-b62f-178c39264084    INFO    Storing new song
2024-04-26T10:40:02.070Z    81327c7f-65bd-4af6-b62f-178c39264084    INFO    {
  title_hash: { S: '742617000027' },
  album_title: { S: 'Slipknot' },
  number: { N: 1 },
  title: { S: '742617000027' },
  length: { N: 36 },
  artist_name: { S: 'Slipknot' },
  cover_url: {
    S: 'https://i.scdn.co/image/ab67616d0000b273baf04a1d30db6ac9de26da7d'
  },
  plays_total: { N: '0' }
}
2024-04-26T10:40:02.410Z    81327c7f-65bd-4af6-b62f-178c39264084    ERROR   Invoke Error    {"errorType":"ValidationException","errorMessage":"One or more parameter values were invalid: Type mismatch for key title_hash expected: S actual: M","name":"ValidationException","$fault":"client","$metadata":{"httpStatusCode":400,"requestId":"2BEM4S6PUNFUEIJ826L49C8TQ7VV4KQNSO5AEMVJF66Q9ASUAAJG","attempts":2,"totalRetryDelay":91},"__type":"com.amazon.coral.validate#ValidationException","message":"One or more parameter values were invalid: Type mismatch for key title_hash expected: S actual: M","stack":["ValidationException: One or more parameter values were invalid: Type mismatch for key title_hash expected: S actual: M","    at throwDefaultError (/var/runtime/node_modules/@aws-sdk/node_modules/@smithy/smithy-client/dist-cjs/index.js:838:20)","    at /var/runtime/node_modules/@aws-sdk/node_modules/@smithy/smithy-client/dist-cjs/index.js:847:5","    at de_CommandError (/var/runtime/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:2150:14)","    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)","    at async /var/runtime/node_modules/@aws-sdk/node_modules/@smithy/middleware-serde/dist-cjs/index.js:35:20","    at async /var/runtime/node_modules/@aws-sdk/lib-dynamodb/dist-cjs/index.js:158:30","    at async /var/runtime/node_modules/@aws-sdk/node_modules/@smithy/core/dist-cjs/index.js:165:18","    at async /var/runtime/node_modules/@aws-sdk/node_modules/@smithy/middleware-retry/dist-cjs/index.js:320:38","    at async /var/runtime/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js:33:22","    at async exports.handler (/var/task/index.js:48:18)"]}
END RequestId: 81327c7f-65bd-4af6-b62f-178c39264084
解决方案

问题出在混用了低级DynamoDB客户端和**文档客户端(DynamoDBDocumentClient)**的参数格式:

  • 直接用DynamoDBClient时,需要指定{ "S": "string" }这类原生DynamoDB类型格式
  • 但你用的DynamoDBDocumentClient会自动处理类型转换,不需要手动加S/N这些标识

修改方法如下,去掉Item里的类型包装,直接传原始值:

putItemCommandInput.Item = {
    title_hash: strip(event.title), // 直接传字符串,无需{S: ...}
    album_title: event.album_title,
    number: event.number, // 数字直接传,文档客户端自动转成N类型
    title: event.title,
    length: event.length,
    artist_name: event.artist_name,
    cover_url: event.cover_url,
    plays_total: 0, // 用数字0而非字符串"0"
};

额外注意细节:

  • 如果event.number或event.length是字符串格式的数字,需要先转成数字(比如parseInt(event.number)),避免类型识别错误
  • 日志里显示的格式看似正确,但DynamoDBDocumentClient会把你传入的{S: ...}当成Map对象(即错误里的M类型),而非解析为字符串,这就是报错的核心原因

内容的提问来源于stack exchange,提问作者fudo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 07:20:56