DynamoDB is a fully managed NoSQL database service provided by Amazon Web Services (AWS). It gives a fast and predictable performance with seamless scalability, making it ideal for applications requiring low latency and high throughput. On the other hand, Node.js is a popular server-side JavaScript runtime widely used for building scalable and efficient web applications.
This Answer demonstrates how to retrieve data from DynamoDB using Node.js. Learn the basics of DynamoDB, such as tables, members, properties, and interacting with databases using the AWS SDK for Node.js. Let’s first see the packages required to use DynamoDB.
To use DynamoDB with Node.js. We need to install aws-sdk
in the root directory of our project using the following command:
npm install aws-sdk@2.1351.0
We can also add the dependency in our package.json
file.
After we have successfully installed the aws-sdk
module. It will be present in the node_modules
directory inside our project folder.
To configure DynamoDB with our Nodejs. We are using the following config.js
file:
module.exports = {aws_table_name: 'Movies',aws_local_config: {//Provide details for local configuration here},aws_remote_config: {accessKeyId: "Your accessKeyId here",secretAccessKey: "Your secretAccessKey here",region: 'us-east-1',}};
The file above exports a JavaScript object containing configuration details related to AWS (Amazon Web Services) for a module to use.
The object has three properties:
aws_table_name
: A string value containing the name of the AWS DynamoDB table called Movies
.
aws_local_config
: An object containing details for the local configuration of AWS. This property is left empty and requires a user to provide its details.
aws_remote_config
: An object containing details for the remote configuration of AWS. This property contains three key-value pairs:
accessKeyId
: A string value representing the access key ID of the AWS user who has permission to access the Movies
table.
secretAccessKey
: A string value representing the secret access key of the AWS user who has permission to access the Movies
table.
region
: A string value representing the AWS region where the Movies
table is located (in this case, us-east-1
).
Now, let’s write some code to create, add, retrieve, and delete a table.
First up, let's import the required modules and configurations:
const AWS = require('aws-sdk');const config = require('../config.js');// Setting the configurationsAWS.config.update(config.aws_remote_config);
As mentioned, we will write code for the following functions.
Creating the table
Inserting the data
Viewing the data
Deleting the table
Now, let's write our code for creating a Movies
table:
// Creating the table named "Movies"var createMoviesTable = function(callback) {// Making a DynamoDB instancevar dynamodb = new AWS.DynamoDB();// Providing table name, attribute name etc as paramsvar params = {TableName : "Movies",KeySchema: [{ AttributeName: "movieName", KeyType: "HASH"},{ AttributeName: "movieType", KeyType: "RANGE"}],AttributeDefinitions: [{ AttributeName: "movieName", AttributeType: "S" },{ AttributeName: "movieType", AttributeType: "S" }],ProvisionedThroughput: {ReadCapacityUnits: 5,WriteCapacityUnits: 5}};// Call DynamoDB to create the tableawait dynamodb.createTable(params, function(err, data) {if (err) {console.log("Error", err);} else {console.log("Table Created", data);}});};
Now, let's add a code for adding a movie to our Movies
database.
//Adding a movie named "Lion King"const addMovie = function (req, res) {// Create the DynamoDB service objectvar dynamodb = new AWS.DynamoDB();var params = {TableName: "Movies",Item: {'movieName' : {S: 'Lion King'},'movieType' : {S: 'Animation'}}};// Call DynamoDB to add the item to the tableawait dynamodb.putItem(params, function(err, data) {if (err) {console.log("Error", err);} else {console.log("Success", data);}});};
Now, let's write a code for whether Lion King
was inserted in our Movies
table or not.
// Fetching our added movieconst getMovies = function (req, res) {var docClient = new AWS.DynamoDB.DocumentClient();var params = {TableName: "Movies",KeyConditionExpression: "movieName = :name",ExpressionAttributeValues: {":name": "Lion King"}};await docClient.query(params, function(err, data) {if (err) {console.log("Error", err);} else {console.log("Query succeeded:", JSON.stringify(data, null, 2));}});};
Next, we need to delete our Movies
table to save resources and money.
// Deleting the table at the end.const deleteMovieTable = function (req, res) {var dynamodb = new AWS.DynamoDB(); //low-level clientvar tableName = "Movies";var params = {TableName : "Movies"};await dynamodb.deleteTable(params, function(err, data) {if (err) {console.error("Unable to delete table. Error JSON:", JSON.stringify(err, null, 2));} else {console.log("Deleted table. Table description JSON:", JSON.stringify(data, null, 2));}});}
Now, let's run our written to verify whether the code is working fine or not.
Let’s run our code and see what we see in the console below.
Note: We need to provide our own
accessKeyId
andsecretAccessKey
in place of "Your accessKeyId here" and "Your secretAccessKey here" respectively to make things work.
Provide the credentials and uncomment lines from 110 to 113 one by one (which means that only uncomment the function which we want to call and comment out all the other functions) to see the logs in the console below.
Note: Uncommenting more than one function call may result in errors.
Lines 1–4: We import the required modules and configurations.
Lines 8–24: We create a function named createMoviesTable
. We define the table name, schema, and so on. Then, create a table named Movies
in DynamoDB using the dynamodb.createTable
function.
Lines 38–58: We create a function named getMovies
. We define the params
including table name, etc., and then we get the data from the Movies
table using docClient.query
function.
Lines 61–82: We create a function named addMovie
. We define the params
including table name, data, and so on. Then, we insert the data in the Movies
table using dynamodb.putItem
function.
Lines 85–101: We create a function named deleteMovieTable
. We define the params
including the table name, and then we delete the Movies
table using dynamodb.deleteTable
function.
Lines 103–106: We call the createMoviesTable
, addMovie
, getMovies
, and deleteMovieTable
functions in sequence.
Free Resources