0
votes

I want to retrieve just ONE item from a DynamoDB table ("todosTable") with partitionKey = userID and sortKey = todoID.

Just to show you something, below there is an example that correctly gets ALL the todo items for a user with userId=userId

 async getAllTodos(userId: string): Promise<TodoItem[]>{

    const result = await this.docClient.query({
      TableName: this.todosTable,
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: {
        ':userId': userId
      }
    }).promise()
    return result.Items as TodoItem[]
  }

But that is not what I want. I want just one item. As per the documentation, I will use a key condition expression that acts upon Primary keys(partition and/or sort key)

So I tried to do it this way but this is incorrect

async getTodoItem1(userId: string, todoId: string): Promise<TodoItem>{

    const result = await this.docClient.get({
      TableName: this.todosTable,
      KeyConditionExpression: 'userId = :userId',
      AND todId = :todoId,
      ExpressionAttributeValues: {
        ':userId': userId,
        ':todoId': todoId
      }
    }).promise()

    return result.Item
  }

Could someone please help me get the correct query that retrieves just one item, where partition key = userID and sort key = todoID ?

Is the correct pattern to use a GlobalSecondaryIndex in this case?

Thanks

1

1 Answers

2
votes

You'll need to add the secondary key to the KeyConditionExpression as well, should look something like this:

KeyConditionExpression: 'userId = :userId AND todoId = :todoId'

The sort key is more flexible and allows for other operations like BEGINS_WITH, BETWEEN etc