Introduction
The document client abstraction makes it easy to work with DynamoDB by letting you use simple JavaScript objects instead of complex low-level commands.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, PutCommand, GetCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({ region: "your-region" }); const docClient = DynamoDBDocumentClient.from(client); // To put an item await docClient.send(new PutCommand({ TableName: "YourTableName", Item: { key1: "value1", key2: 123 } })); // To get an item const result = await docClient.send(new GetCommand({ TableName: "YourTableName", Key: { key1: "value1" } }));
await docClient.send(new PutCommand({ TableName: "Users", Item: { userId: "123", name: "Alice", age: 30 } }));
const data = await docClient.send(new GetCommand({ TableName: "Users", Key: { userId: "123" } })); console.log(data.Item);
// Edge case: Getting an item that does not exist const data = await docClient.send(new GetCommand({ TableName: "Users", Key: { userId: "999" } })); console.log(data.Item); // undefined
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, PutCommand, GetCommand } from "@aws-sdk/lib-dynamodb"; async function run() { const client = new DynamoDBClient({ region: "us-east-1" }); const docClient = DynamoDBDocumentClient.from(client); console.log("Before putting item:"); let getResult = await docClient.send(new GetCommand({ TableName: "TestTable", Key: { id: "1" } })); console.log(getResult.Item); // Should be undefined if no item await docClient.send(new PutCommand({ TableName: "TestTable", Item: { id: "1", name: "John Doe", age: 25 } })); console.log("After putting item:"); getResult = await docClient.send(new GetCommand({ TableName: "TestTable", Key: { id: "1" } })); console.log(getResult.Item); // Should show the inserted item } run().catch(console.error);
const params = { TableName: "Users", Key: { userId: "123" } };
const command = new GetCommand(params);
const data = await docClient.send(command);
console.log(data.Item);const params = { TableName: "Products", Item: { id: 101, name: "Pen" } };
const command = new GetCommand(params);
const result = await docClient.send(command);
console.log(result);Pass the test and this pattern moves unknown