查询条件缺少具有二级索引字段的关键模式元素

Query condition missed key schema element with a secondary index field

第一次接触dynamodb和serverless框架。我正在尝试创建一个简单的待办事项应用程序。以todoId为主键,userId为二级索引。这是我在 serverless.yaml 中对 table 的定义,但是当我尝试获取用户的待办事项列表时,出现上述错误。

resources:
  Resources:
    GroupsDynamoDBTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDefinitions:
          - AttributeName: todoId
            AttributeType: S
          - AttributeName: userId
            AttributeType: S

        KeySchema:
          - AttributeName: todoId
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
        TableName: ${self:provider.environment.TODOLIST_TABLE}
        GlobalSecondaryIndexes:
          - IndexName: ${self:provider.environment.USER_ID_INDEX}
            KeySchema:
            - AttributeName: userId
              KeyType: HASH
            Projection:
              ProjectionType: ALL

查询:

  const result = await docClient
    .query({
      TableName: toDoListTable,
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: {
        ':userId': 5
      },
      ScanIndexForward: false
    })
    .promise()

由于您正在使用全局二级索引进行查询,因此您必须指定要使用的索引的名称以及要在查询结果中返回的属性。

结果应该是这样的:

const result = await docClient
    .query({
      TableName: toDoListTable,
      IndexName: "UserIdIndex", // the name specified here: self:provider.environment.USER_ID_INDEX
      KeyConditionExpression: "userId = :userId",
      ExpressionAttributeValues: {
        ":userId": 5
      },
      ProjectionExpression: "todoId, userId",
      ScanIndexForward: false
    })
    .promise()