Node.js - DynamoDB examples within async functions

The following examples uses a hash key attr1 and a range key attr2.

A simple get example within an async function.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, GetCommand } = require("@aws-sdk/lib-dynamodb");

(async function() {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient({ region: "us-east-1" });
  
  // Create the Document Client from the DynamoDB client
  const docClient = DynamoDBDocumentClient.from(client);

  let getResult;
  try {
    // Prepare the GetCommand with ProjectionExpression and ExpressionAttributeNames
    const command = new GetCommand({
      TableName: "TABLE_NAME",
      Key: {
        attr1: "val1",
        attr2: "val2"
      },
      ConsistentRead: false,
      ReturnConsumedCapacity: "NONE",
      ProjectionExpression: "#a1, #a2, #a3", // For filtering response items. Optional with ExpressionAttributeNames
      ExpressionAttributeNames: { // Optional with ProjectionExpression
        "#a1": "attr1",
        "#a2": "attr2"
      }
    });

    // Send the command using the document client
    getResult = await docClient.send(command);
  } catch (e) {
    console.error(`Could not get from DynamoDB: ${e.message}`);
    return;
  }

  // Check if the item is found
  if (!getResult || !getResult.Item) {
    console.log(`No item found:`, JSON.stringify(getResult));
    return;
  }

  // Print the retrieved attributes
  console.log(`attr1: ${getResult.Item["attr1"]} and attr2: ${getResult.Item["attr2"]}`);
})();

A simple scan example within an async function.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, ScanCommand } = require("@aws-sdk/lib-dynamodb");

// Create an instance of DynamoDBClient
const client = new DynamoDBClient({ region: "us-east-1" });

// Create a DocumentClient from the DynamoDB client
const documentClient = DynamoDBDocumentClient.from(client);

(async function() {
  let scanResult;
  try {
    // Use the ScanCommand to scan the table
    const command = new ScanCommand({
      TableName: "TABLE_NAME",
      Limit: 1000,
      ConsistentRead: false,
      ReturnConsumedCapacity: "NONE"
    });

    // Send the command
    scanResult = await documentClient.send(command);
    
  } catch (e) {
    console.error(`Could not get from DynamoDB: ${e.message}`);
    return;
  }
  
  // Check if the result is empty
  if (!scanResult || !Array.isArray(scanResult.Items) || scanResult.Items.length === 0) {
    console.log(`No items in scan result:`, JSON.stringify(scanResult));
    return;
  }
  
  // Print all items
  for (const item of scanResult.Items) {
    console.log(`attr1: ${item["attr1"]} and attr2: ${item["attr2"]}`);
  }
})();

A simple query example within an async function.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, QueryCommand } = require("@aws-sdk/lib-dynamodb");

const client = new DynamoDBClient({ region: "us-east-1" });
const docClient = DynamoDBDocumentClient.from(client);

(async function() {
  let queryResult;
  try {
    const command = new QueryCommand({
      TableName: "TABLE_NAME",
      ConsistentRead: false,
      ExpressionAttributeNames: {
        "#attr1": "attr1"
      },
      ExpressionAttributeValues: {
        ":attr1": "val1"
      },
      KeyConditionExpression: "#attr1 = :attr1",
      ProjectionExpression: "attr1,attr2",
      ReturnConsumedCapacity: "NONE",
      ScanIndexForward: false
    });

    queryResult = await docClient.send(command);
  } catch (e) {
    console.error(`Could not query DynamoDB: ${e.message}`);
    return;
  }

  // Empty?
  if (!queryResult || !Array.isArray(queryResult.Items) || queryResult.Items.length === 0) {
    console.log(`No items in query result:`, JSON.stringify(queryResult));
    return;
  }

  // Print all
  for (const item of queryResult.Items) {
    console.log(`attr1: ${item["attr1"]} and attr2: ${item["attr2"]}`);
  }
}
})();

Another query example using a secondary index within an async function.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, QueryCommand } = require("@aws-sdk/lib-dynamodb");

const client = new DynamoDBClient({ region: "us-east-1" });
const docClient = DynamoDBDocumentClient.from(client);

(async function() {
  let queryResult;
  try {
    const command = new QueryCommand({
      TableName: "TABLE_NAME",
      IndexName: "INDEX_NAME",
      ConsistentRead: false,
      ExpressionAttributeNames: {
        "#attr1": "attr1"
      },
      ExpressionAttributeValues: {
        ":attr1": "val1"
      },
      KeyConditionExpression: "#attr1 = :attr1",
      ProjectionExpression: "attr1, attr2",
      ReturnConsumedCapacity: "NONE",
      ScanIndexForward: false
    });

    queryResult = await docClient.send(command);

  } catch (e) {
    console.error(`Could not query DynamoDB: ${e.message}`);
    return;
  }

  if (!queryResult || !Array.isArray(queryResult.Items) || queryResult.Items.length === 0) {
    console.log(`No items in query result:`, JSON.stringify(queryResult));
    return;
  }

  for (const item of queryResult.Items) {
    console.log(`attr1: ${item.attr1} and attr2: ${item.attr2}`); // Direct access without .S
  }
})();

Batch get example.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, BatchGetCommand } = require("@aws-sdk/lib-dynamodb");

(async function() {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient({ region: "us-east-1" });
  
  // Create the Document Client from the DynamoDB client
  const docClient = DynamoDBDocumentClient.from(client);

  let batchGetResult;
  try {
    // Prepare the BatchGetCommand
    const command = new BatchGetCommand({
      RequestItems: {
        "TABLE_NAME": {
          Keys: [
            { attr1: "val1", attr2: "val2" },
            { attr1: "val3", attr2: "val4" }
          ],
          ProjectionExpression: "#a1, #a2",
          ExpressionAttributeNames: {
            "#a1": "attr1",
            "#a2": "attr2"
          }
        }
      },
      ReturnConsumedCapacity: "NONE"
    });

    // Send the command using the document client
    batchGetResult = await docClient.send(command);
  } catch (e) {
    console.error(`Could not batch get from DynamoDB: ${e.message}`);
    return;
  }

  // Check if items are found
  if (!batchGetResult || !batchGetResult.Responses || !batchGetResult.Responses["TABLE_NAME"]) {
    console.log(`No items found:`, JSON.stringify(batchGetResult));
    return;
  }

  // Print the retrieved attributes
  batchGetResult.Responses["TABLE_NAME"].forEach(item => {
    console.log(`attr1: ${item["attr1"]} and attr2: ${item["attr2"]}`);
  });
})();

Single write example.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { PutCommand } = require("@aws-sdk/lib-dynamodb");

const client = new DynamoDBClient({ region: "us-east-1" });

(async function() {
  try {
    const command = new PutCommand({
      TableName: "TABLE_NAME",
      Item: {
        "attr1": "val1",
        "attr2": "val2"
      }
    });
    
    await client.send(command);
    
    console.log("Saved to DynamoDB");
    
  } catch (e) {
    console.error(`Could not save to DynamoDB: ${e.message}`);
  }
})();

Batch write example.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, BatchWriteCommand } = require("@aws-sdk/lib-dynamodb");

// Create a DynamoDB client
const client = new DynamoDBClient({ region: "us-east-1" });

// Create a DynamoDB Document client
const documentClient = DynamoDBDocumentClient.from(client);

(async function() {
  try {
    // Prepare the batch write command
    const command = new BatchWriteCommand({
      RequestItems: {
        "TABLE_NAME": [
          {
            PutRequest: {
              Item: {
                "attr1": "val1",
                "attr2": "val2"
              }
            }
          },
          {
            PutRequest: {
              Item: {
                "attr1": "val1",
                "attr2": "val2"
              }
            }
          },
          {
            DeleteRequest: {
              Key: {
                "attr1": "val1"
              }
            }
          }
        ]
      },
      ReturnConsumedCapacity: "NONE",
      ReturnItemCollectionMetrics: "NONE"
    });

    // Send the batch write command
    await documentClient.send(command);
    
    console.log("Saved to DynamoDB");
    
  } catch (e) {
    console.error(`Could not save to DynamoDB: ${e.message}`);
    return;
  }
})();

Single update example.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, UpdateCommand } = require("@aws-sdk/lib-dynamodb");

// Initialize the DynamoDB Client
const client = new DynamoDBClient({ region: "us-east-1" });

// Create a DynamoDB Document Client
const documentClient = DynamoDBDocumentClient.from(client);

(async function() {
  try {
    // Prepare the update command
    const command = new UpdateCommand({
      TableName: "TABLE_NAME",
      Key: {
        "attr1": "val1",
        "attr2": "val2"
      },
      UpdateExpression: 'ADD #attr3 :one SET #attr4 = #attr4 + :ten', // Increment attr3 by 1 and attr4 by 10
      ConditionExpression: '#attr3 < :max',
      ExpressionAttributeNames: {
        "#attr3" : "attr3",
        "#attr4" : "attr4"
      },
      ExpressionAttributeValues: {
        ":one": 1,
        ":ten": 10,
        ":max" : 100
      }
    });

    // Send the update command
    await documentClient.send(command);
    console.log("Saved to DynamoDB");
    
  } catch (e) {
    console.error(`Could not save to DynamoDB: ${e.message}`);
    return;
  }
})();

Delete example.

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, DeleteCommand } = require("@aws-sdk/lib-dynamodb");

// Initialize the DynamoDB client
const client = new DynamoDBClient({ region: "us-east-1" });
const documentClient = DynamoDBDocumentClient.from(client);

(async function() {
  try {
    // Create a delete command
    const command = new DeleteCommand({
      TableName: "TABLE_NAME",
      Key: {
        "attr1": "val1",
        "attr2": "val2"
      },
      ReturnConsumedCapacity: "NONE",
      ReturnItemCollectionMetrics: "NONE",
      ReturnValues: "NONE"
    });

    // Send the delete command
    await documentClient.send(command);
      
    console.log("Deleted from DynamoDB");
    
  } catch (e) {
    console.error(`Could not delete from DynamoDB: ${e.message}`);
    return;
  }
})();