A Lambda function lets you run code automatically when something happens. Using it with DynamoDB helps you save or get data without managing servers.
Lambda function with DynamoDB
Introduction
Syntax
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'YourTableName', Key: { id: event.id } }; try { const data = await dynamo.get(params).promise(); return data.Item; } catch (error) { return { error: error.message }; } };
This is a simple Lambda function in Node.js that reads an item from DynamoDB.
Replace 'YourTableName' and 'id' with your actual table and key names.
Examples
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Users', Item: { id: event.id, name: event.name } }; await dynamo.put(params).promise(); return { message: 'User saved' }; };
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Users', Key: { id: event.id } }; const data = await dynamo.get(params).promise(); return data.Item || { message: 'User not found' }; };
Sample Program
This Lambda function saves a product to the 'Products' table and then retrieves it to confirm it was saved.
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Products', Item: { id: '101', name: 'Coffee Mug', price: 12.99 } }; try { await dynamo.put(params).promise(); const getParams = { TableName: 'Products', Key: { id: '101' } }; const data = await dynamo.get(getParams).promise(); return data.Item; } catch (error) { return { error: error.message }; } };
Important Notes
Make sure your Lambda has permission to access DynamoDB.
Use AWS SDK's DocumentClient for easier JSON handling.
Always handle errors to avoid crashes.
Summary
Lambda functions let you run code triggered by events without servers.
Use AWS SDK's DocumentClient to read and write DynamoDB data easily.
Remember to set correct permissions and handle errors in your code.
Practice
1. What is the main purpose of using a Lambda function with DynamoDB in AWS?
easy
Solution
Step 1: Understand Lambda triggers
Lambda functions can be triggered by events, such as changes in DynamoDB tables.Step 2: Identify the purpose of automation
This allows automatic code execution when data changes, without manual intervention.Final Answer:
To run code automatically when DynamoDB data changes -> Option AQuick Check:
Lambda triggers = automatic code run [OK]
Hint: Lambda runs code on events like DynamoDB changes [OK]
Common Mistakes:
- Thinking Lambda manually updates tables
- Confusing Lambda with backup tools
- Assuming Lambda creates tables automatically
2. Which of the following is the correct way to initialize AWS DynamoDB DocumentClient in a Node.js Lambda function?
easy
Solution
Step 1: Recall correct DocumentClient syntax
The AWS SDK requires using 'new' keyword to create a DocumentClient instance.Step 2: Match correct class name and usage
The correct class is AWS.DynamoDB.DocumentClient, not DynamoDBClient or Document.Final Answer:
const docClient = new AWS.DynamoDB.DocumentClient(); -> Option BQuick Check:
Use 'new' with DocumentClient class [OK]
Hint: Use 'new AWS.DynamoDB.DocumentClient()' to initialize [OK]
Common Mistakes:
- Omitting 'new' keyword
- Using wrong class name like DynamoDBClient
- Calling Document() instead of DocumentClient
3. Given this Lambda function snippet, what will be the output if the item with id '123' exists in the DynamoDB table?
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
const params = {
TableName: 'Users',
Key: { id: '123' }
};
const data = await docClient.get(params).promise();
return data.Item;
};medium
Solution
Step 1: Understand docClient.get usage
The get method retrieves a single item by key from the specified table.Step 2: Analyze the return value
If the item with id '123' exists, data.Item will contain that item object.Final Answer:
The item object with id '123' from the Users table -> Option DQuick Check:
docClient.get returns item if found [OK]
Hint: docClient.get returns single item by key [OK]
Common Mistakes:
- Expecting a list instead of single item
- Thinking get method is invalid
- Assuming empty object if item exists
4. Identify the error in this Lambda function code that writes an item to DynamoDB:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
const params = {
TableName: 'Products',
Item: {
productId: '001',
name: 'Book'
}
};
await docClient.putItem(params).promise();
return 'Success';
};medium
Solution
Step 1: Check DocumentClient method names
DocumentClient uses 'put' method, not 'putItem'.Step 2: Confirm correct method usage
Using 'putItem' causes a runtime error because it does not exist on DocumentClient.Final Answer:
Using 'putItem' instead of 'put' method on DocumentClient -> Option AQuick Check:
Use 'put' to write items with DocumentClient [OK]
Hint: Use 'put', not 'putItem', with DocumentClient [OK]
Common Mistakes:
- Confusing low-level DynamoDB client with DocumentClient
- Assuming 'putItem' exists in DocumentClient
- Ignoring method naming conventions
5. You want a Lambda function to update a user's email in DynamoDB only if the user exists. Which approach correctly ensures this conditional update?
hard
Solution
Step 1: Understand conditional update in DynamoDB
To update only if an item exists, use ConditionExpression with 'attribute_exists' on the key.Step 2: Apply ConditionExpression in update method
docClient.update supports ConditionExpression to prevent overwriting non-existing items.Step 3: Evaluate other options
Using put without condition overwrites or creates new items; delete before update is inefficient; get then put is not atomic.Final Answer:
Use docClient.update with ConditionExpression 'attribute_exists(id)' -> Option CQuick Check:
Conditional update = update + attribute_exists [OK]
Hint: Use ConditionExpression 'attribute_exists' for safe updates [OK]
Common Mistakes:
- Using put which overwrites without condition
- Deleting item before update unnecessarily
- Not using atomic conditional update
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
