首页 > 解决方案 > 按 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" }
    }' \

任何帮助,将不胜感激!

谢谢,

蒂姆

标签: amazon-dynamodbserverless-frameworkaws-amplify

解决方案


推荐阅读