我在尝试从DynamoDB表中检索项目时遇到问题。我正在尝试通过其ID检索一项,但出现错误:ValidationException: The provided key element does not match the schema
。
我已经登录event.pathParameters.id
,并且返回了我期望的ID,但正在努力找出正确的语法。
contactId
是表上的主分区键。
我有一个userId
主键-这是问题吗?我是否还必须使用排序键才能检索记录。
dynamo-lib.js
import AWS from 'aws-sdk';
export function call(action, params) {
const dynamoDb = new AWS.DynamoDB.DocumentClient();
return dynamoDb[action](params).promise();
}
get.js
import * as dynamoDbLib from '../libs/dynamodb-lib';
import { success, failure } from '../libs/response-lib';
export async function getReferralDetails(event, context) {
const params = {
TableName: 'contacts',
KeyConditionExpression: 'contactId = :contactId',
ExpressionAttributeValues: {
':contactId': event.pathParameters.id
}
};
try {
const result = await dynamoDbLib.call('query', params);
if (result.Item) {
// Return the retrieved item
return success(result.Item);
} else {
console.log(result);
return failure({ status: false, error: 'Item not found.' });
}
} catch (e) {
console.log(e);
return failure({ status: false });
}
}
表架构
{
"Table": {
"TableArn": "arn:***",
"AttributeDefinitions": [
{
"AttributeName": "contactId",
"AttributeType": "S"
},
{
"AttributeName": "userId",
"AttributeType": "S"
}
],
"ProvisionedThroughput": {
"NumberOfDecreasesToday": 0,
"WriteCapacityUnits": 0,
"ReadCapacityUnits": 0
},
"TableSizeBytes": 0,
"TableName": "contacts",
"TableStatus": "ACTIVE",
"TableId": "b54a6d62-70f6-4c6a-9d91-60abef38615f",
"KeySchema": [
{
"KeyType": "HASH",
"AttributeName": "contactId"
},
{
"KeyType": "RANGE",
"AttributeName": "userId"
}
],
"ItemCount": 0,
"CreationDateTime": 1563814200.835
}
}
奇怪的是-如果我在终端中运行以下命令。它给了我记录。
aws dynamodb query \
--table-name contacts \
--key-condition-expression "contactId = :contactId" \
--expression-attribute-values '{
":contactId": { "S": "9902ae80-aca2-11e9-8de1-9329be074f3b" }
}' \
任何帮助将不胜感激!
谢谢
蒂姆