amazon-dynamodb - 按 ID 获取项目不适用于 DynamoDB
问题描述
我在尝试从 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();
}
获取.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" }
}' \
任何帮助,将不胜感激!
谢谢,
蒂姆
解决方案
推荐阅读
- c - 在 ARM 中执行不会跳出循环
- java - 如何停止替换共享首选项中的先前条目?
- xml - 使用 sed 换行。sed 不一致或者我犯了一个大错误
- java - 添加 void addFoodFirst(String foodName) 仅使用 1 条语句在食物的开头添加 foodName 作为第一个元素
- r - 无法发布到 shinyapps.io
- php - Laravel 5 loadJsonTranslationsFrom 方法不会从包中加载所有 JSON 翻译文件
- matlab - 在 MATLAB 中为“现在”设置特定时间
- kubectl - 如何使用代理服务器进行 kubectl?
- python - 如何使用 matplotlib 或 plotly 在 3-D 曲面图上叠加等高线图?
- php - Flutter Unhandled Exception: FormatException: Unexpected character (at character 4)