Search code examples
amazon-dynamodbdynamodb-queriesaws-sdk-nodejs

DynamoDB result is not structured the way I want


I am doing a simple command to list all the items in my table. However, the data I am getting back is not structured the way I want. I want a simple JSON structure but DynamoDB is turning the results into nested objects.

DynamoDB gives me below response:

// What I am currently getting
[
  {
    id: { S: '8' },
    lastName: { S: 'Perry' },
    firstName: { S: 'Matthew' }
  },
  {
    id: { S: '3' },
    firstName: { S: 'Joan' },
    lastName: { S: 'Peter' }
  }
]

But I want this:

// What I want
[
  {
    id: 8
    lastName:  'Perry' ,
    firstName: 'Matthew' 
  },
  {
    id: 3,
    firstName: 'Joan' ,
    lastName:  'Peter' 
  }
]

How can I achieve the later result set. Below is my code:

const { ExecuteStatementCommand } = require('@aws-sdk/client-dynamodb') 
const { ddbDocClient, memberTableName } = require('./client.js')

const selectAll = async () => {
    const params = {
        Statement: `SELECT * FROM ${memberTableName}`,
        Parameters: [{ S: '3' }]
    }
    console.log(params)
    return await ddbDocClient.send(new ExecuteStatementCommand(params));
}


selectAll()
.then(d => console.log(d.Items))

ddbDocClient was created like this:

 const ddbDocClient = DynamoDBDocumentClient.from(ddbClient);

Solution

  • The command import is incorrect. To send and receive native JS types, import the ExecuteStatementCommand command from the @aws-sdk/lib-dynamodb "document client" package.

    const { ExecuteStatementCommand } = require('@aws-sdk/lib-dynamodb');
    

    You are importing the command from the "regular client" package @aws-sdk/client-dynamodb, i.e. the one that accepts and returns DynamoDB JSON.

    Note: The Parameters: [{ S: '3' }] line is also wrong, but it's currently not causing trouble because your statement is scanning for all records. If you were to include a WHERE id=? phrase in the statement, make sure to change the parameters to Parameters: ['3']. You must pass JS types to the "document client" commands.