温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.muo.com/aws-dynamodb-nodejs-application/
点击访问原文链接

Using AWS DynamoDB in a Node.js Application

Using AWS DynamoDB in a Node.js Application Menu Sign in now Close Trending Submenu Productivity Android Smart TVs Networking Windows 11 Entertainment PC & Mobile Submenu Windows2 Linux Android Apple Technical Submenu Tech Explained Security Software Submenu Productivity Internet Creative Screen Submenu Entertainment Streaming Home Submenu Smart Home Home News Sign in Newsletter Menu Follow Followed Like More Action Sign in now Productivity Android Smart TVs Networking Windows 11 Entertainment Close
Using AWS DynamoDB in a Node.js Application Design by Timilehin Omolana --no attribution required Follow Followed Like Link copied to clipboard Add us on By  Timilehin Omolana Published Nov 7, 2023, 2:00 PM EST Timilehin is a skilled software engineer and technical writer with an undying passion for building secure and scalable server-side systems with Go, Node.js, C++ and AWS.

Timilehin has worked professionally on multiple backend systems since 2020 and currently works on the backend team of an aerospace startup where he builds autopilot software for UAVs. Sign in to your MakeUseOf account Summary DynamoDB is a powerful NoSQL database offered by AWS that can handle large amounts of diverse data without compromising performance, durability, or reliability. To get started with DynamoDB in Node.js, you need to install the client-dynamodb package from the aws-sdk and configure your credentials. DynamoDB allows you to easily create tables, write and read data, update records, and delete records using the client's methods and parameters. It offers flexibility and scalability for efficient application development.

A large part of modern app development needs a mix of robust programming languages and powerful databases.

One of the solutions that Amazon Web Services (AWS) offers is DynamoDB, a tool that can revolutionize your data management. Using it, you can quickly provision a database to handle large amounts of diverse data.

What Is DynamoDB?

AWS offers services for different database needs, like Amazon RDS for relational databases, and DocumentDB for document databases such as MongoDB. DynamoDB is a NoSQL database for storing data in a key-value format.

DynamoDB can handle large amounts of data across distributed infrastructure without compromising performance, durability, or reliability. It offers a flexible model, letting you easily store and query data, whether it’s structured or unstructured.

You can use DynamoDB as the database for various types of application. You can access it directly from the AWS web console and programmatically via the AWS-CLI, or from web applications using the AWS-SDK.

Getting Started With DynamoDB in Node.js

There are many tools for building backend APIs in Node.js and you're free to choose the database for your API when working with any of these tools. Node.js provides wide support for external services including databases like AWS DynamoDB.

All you need to access an AWS service from your Node app is the client aws-sdk package for that service. For instance, to access DynamoDB, you need to install the client-dynamodb package under aws-sdk.

Run this command in your project directory to install the package:

npm install @aws-sdk/client-dynamodb

After installing aws-sdk/client-dynamodb in your Node.js project, you need to add the region of your DynamoDB table to the configuration before you interact with it. You will do this when initializing the DynamoDB client.

If you have installed and used AWS-CLI on your computer before, you probably have AWS credentials set in your environment already, and the SDK will automatically get your values from the environment.

But if you haven’t, you can head to the AWS Identity Access Management (IAM) service in your console and create a new user. After creating the user, you can get an access key ID and secret key, which are your personal credentials.

Add these credentials to your environment by running the following terminal commands for your platform:

On Unix, Linux, or macOS:

export AWS_ACCESS_KEY_ID='your access key ID'
export AWS_SECRET_ACCESS_KEY='you secret access key'

On Windows (CMD):

set AWS_ACCESS_KEY_ID='your access key ID'
set AWS_SECRET_ACCESS_KEY='you secret access key'

On Windows (PowerShell):

$env:AWS_ACCESS_KEY_ID='your access key ID'
$env:AWS_SECRET_ACCESS_KEY='you secret access key'

Then, back in your Node.js project, create a new file and name it dynamodb.js. In this file, instantiate a new AWS DynamoDB client using the following code:

const { DynamoDB } = require('@aws-sdk/client-dynamodb')

const region = "us-east-1" // your preferred region

const client = new DynamoDB({ region })

Pretty simple! AWS makes sure you are not exposing any of your security credentials in your code, so while the code above tries to create the client, it first reads the access key and secret key from your environment.

The newly-created client enables you to carry out various operations, like creating tables and reading and writing data.

DynamoDB is schema-less just like other NoSQL databases, so you can always add new attributes (fields) to a table at any point. This is why you only need to add attributes that will serve as primary keys to a DynamoDB table when creating it.

Check out the following code which creates a new table (Customer) in DynamoDB:

const createCustomerTable = async () => {
const params = {
TableName: "Customer",
AttributeDefinitions: [
{
AttributeName: "Email",
AttributeType: "S"
},
],
KeySchema: [
{
AttributeName: "Email",
KeyType: "HASH"
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
};

client.createTable(params, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
}

createCustomerTable();

The AttributeDefinitions field is where you define the table’s key attributes and their types. The Email attribute here has type S which means the field expects a String as its value. The three available attribute types are S, N, and B (String, Number, and Binary).

You need the KeySchema to define primary keys which help to find and organize items quickly. DynamoDB expects the attributes you add when creating the table to be key attributes, so Email is the primary key here. You must add it to the KeySchema and specify its KeyType (HASH).

The other available KeyType value is RANGE which is used for sort keys. Sort keys are useful in cases where you might have data with the same HASH keys in a table, and you want to group them according to some extra data such as date or color, you can make the extra data a RANGE key.

The third important parameter in the above code is the ProvisionedThroughput. This is where you define the number of reads and writes you want DynamoDb to allow on the table per second.

When you run the code above, you should get output that looks like this:

screenshot by Timilehin Omolana --no attribution required

If you check your DynamoDB tables dashboard in the web console, you will see the table either still being provisioned or with a status of active already.

Always consider your application needs when specifying the ReadCapacityUnits and WriteCapacityUnits because an inappropriate value can lead to performance problems or high billing costs on your account.

Once you’re sure the table is already active, you can perform CRUD operations on it.

The following are some code examples that show you how to write and read data from the Customer table.

Add data to the table. To write data to a table, you need the client’s putItem method. The code below adds a new customer to the Customer table in DynamoDB.
const createCustomer = async (customer) => {
const params = {
TableName: "Customer",
Item: customer
}

client.putItem(params, (err, data) => {
if (err) {
console.error(err)
} else {
console.log(data)
}
})
}

const customerData = {
Name: { "S": "Timilehin O." },
Email: { "S": "timtim@example.com" },
Age: { "N": "18"},
Country: { "S": "Nigeria" }
}

createCustomer(customerData)
The params object contains the TableName which is the table you’re writing to, and the Item field which contains the data you’re adding with their specific types. Notice the new fields that weren’t in the table initially, this is how DynamoDB works flexibly. You can view the data in your database in your console like this: Screenshot by Timilehin Omolana --no attribution required Read data from the table. DynamoDB allows you to read data in various ways. The SDK’s scan function reads the whole table, while getItem reads only specific data. For instance, the code below gets all customers:
const getAllCustomers = async () => {
const params = {
TableName: "Customer"
}

const customers = await client.scan(params)
console.log(customers)
}
While the following code gets the user by the email value:
const getCustomerByEmail = async (email) => {
const params = {
TableName: "Customer",
Key: {
Email: { "S": email } // the type is always required
}
}

const customer = await client.getItem(params)
console.log(customer)
}

getCustomerByEmail("timtim@example.com")
Update data in the table. To update existing data in a table, use the SDK’s updateItem function. The following code demonstrates how to update a specific record:
 const updateCustomerLocation = async (email, age) => {
const params = {
TableName: "Customer",
Key: {
Email: { "S": email }
},
UpdateExpression: "SET Age = :newAge",
ExpressionAttributeValues: {
':newAge': { "N": age }
},
ReturnValues: "ALL_NEW"
}

const updatedCustomer = await client.updateItem(params)
console.log(updatedCustomer.Attributes)
}
You can also choose to make your function dynamic by building update expressions from your update data. DynamoDB’s flexibility allows you to handle every operation according to your needs. Delete data from the table. To delete a record from DynamoDB, you need the deleteItem function and the key of the particular record. Here’s how to implement it:
const deleteCustomer = async (email) => {
const params = {
TableName: "Customer",
Key: {
Email: { "S": email }
}
}

client.deleteItem(params, (err, data) => {
if (err) {
console.error(err)
} else {
console.log("Customer deleted successfully")
}
})
}

deleteCustomer("timtim@example.com")
Building Efficient Applications With DynamoDB

Amazon Web Services continues to thrive. It provides an accessible platform you can use to deliver efficient, secure digital solutions. DynamoDB is the perfect choice if you’re looking for a database to get running without worrying about infrastructure or security.

You are now equipped with all you need to get started with DynamoDB in Node.js, and you can confidently choose DynamoDB for your next Node.js application.

Close
Recommended How to Create a Linux Server in the Cloud Using AWS EC2 I repurposed 4 old Apple devices, and now they all do something useful in my home HDMI 2.2 is already making HDMI 2.1 look old There's a BIOS setting that decides whether your RAM speed does anything — most people never touch it Join Our Team Our Audience About Us Press & Events Media Coverage Contact Us Follow Us Advertising Careers Terms Privacy Policies MakeUseOf is part of the Valnet Publishing Group Copyright © 2026 Valnet Inc.

Using AWS DynamoDB in a Node.js Application,AI智能索引,全网链接索引,智能导航,网页索引

    Build this sample app to discover just how easy databases can be.