Using AWS DynamoDB in a Node.js Application

Trending 1 month ago

Key Takeaways

  • DynamoDB is simply a powerful NoSQL database offered by AWS that tin grip ample amounts of divers information without compromising performance, durability, aliases reliability.
  • To get started pinch DynamoDB successful Node.js, you request to instal nan client-dynamodb package from nan aws-sdk and configure your credentials.
  • DynamoDB allows you to easy create tables, constitute and publication data, update records, and delete records utilizing nan client's methods and parameters. It offers elasticity and scalability for businesslike exertion development.

A ample portion of modern app improvement needs a operation of robust programming languages and powerful databases.

One of nan solutions that Amazon Web Services (AWS) offers is DynamoDB, a instrumentality that tin revolutionize your information management. Using it, you tin quickly proviso a database to grip ample amounts of divers data.

What Is DynamoDB?

AWS offers services for different database needs, for illustration Amazon RDS for relational databases, and DocumentDB for document databases specified arsenic MongoDB. DynamoDB is simply a NoSQL database for storing information successful a key-value format.

DynamoDB tin grip ample amounts of information crossed distributed infrastructure without compromising performance, durability, aliases reliability. It offers a elastic model, letting you easy shop and query data, whether it’s system aliases unstructured.

You tin usage DynamoDB arsenic nan database for various types of application. You tin entree it straight from nan AWS web console and programmatically via nan AWS-CLI, aliases from web applications utilizing nan AWS-SDK.

Getting Started With DynamoDB successful Node.js

There are galore tools for building backend APIs successful Node.js and you're free to take nan database for your API erstwhile moving pinch immoderate of these tools. Node.js provides wide support for outer services including databases for illustration AWS DynamoDB.

All you request to entree an AWS work from your Node app is nan customer aws-sdk package for that service. For instance, to entree DynamoDB, you request to instal nan client-dynamodb package nether aws-sdk.

Run this bid successful your task directory to instal nan package:

npm instal @aws-sdk/client-dynamodb

After installing aws-sdk/client-dynamodb successful your Node.js project, you request to adhd nan region of your DynamoDB array to nan configuration earlier you interact pinch it. You will do this erstwhile initializing nan DynamoDB client.

If you person installed and utilized AWS-CLI connected your machine before, you astir apt person AWS credentials group successful your situation already, and nan SDK will automatically get your values from nan environment.

But if you haven’t, you tin caput to nan AWS Identity Access Management (IAM) work successful your console and create a caller user. After creating nan user, you tin get an entree cardinal ID and concealed key, which are your individual credentials.

Add these credentials to your situation by moving nan pursuing terminal commands for your platform:

On Unix, Linux, aliases macOS:

export AWS_ACCESS_KEY_ID='your entree cardinal ID'
export AWS_SECRET_ACCESS_KEY='you concealed entree key'

On Windows (CMD):

group AWS_ACCESS_KEY_ID='your entree cardinal ID'
set AWS_SECRET_ACCESS_KEY='you concealed entree key'

On Windows (PowerShell):

$env:AWS_ACCESS_KEY_ID='your entree cardinal ID'
$env:AWS_SECRET_ACCESS_KEY='you concealed entree key'

Then, backmost successful your Node.js project, create a caller record and sanction it dynamodb.js. In this file, instantiate a caller AWS DynamoDB customer utilizing nan pursuing code:

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

const region = "us-east-1"

const customer = new DynamoDB({ region })

Pretty simple! AWS makes judge you are not exposing immoderate of your information credentials successful your code, truthful while nan codification supra tries to create nan client, it first sounds nan entree cardinal and concealed cardinal from your environment.

The newly-created client enables you to transportation retired various operations, for illustration creating tables and reference and penning data.

DynamoDB is schema-less conscionable for illustration different NoSQL databases, truthful you tin ever adhd caller attributes (fields) to a array astatine immoderate point. This is why you only request to adhd attributes that will service arsenic superior keys to a DynamoDB array erstwhile creating it.

Check retired nan pursuing codification which creates a caller array (Customer) successful 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 section is wherever you specify nan table’s cardinal attributes and their types. The Email property present has type S which intends nan section expects a String arsenic its value. The 3 disposable property types are S, N, and B (String, Number, and Binary).

You request nan KeySchema to specify superior keys which thief to find and shape items quickly. DynamoDB expects nan attributes you adhd erstwhile creating nan array to beryllium cardinal attributes, truthful Email is nan superior cardinal here. You must adhd it to nan KeySchema and specify its KeyType (HASH).

The different disposable KeyType worth is RANGE which is utilized for benignant keys. Sort keys are useful successful cases wherever you mightiness person information pinch nan aforesaid HASH keys successful a table, and you want to group them according to immoderate other information specified arsenic day aliases color, you tin make nan other information a RANGE key.

The 3rd important parameter successful nan supra codification is nan ProvisionedThroughput. This is wherever you specify nan number of sounds and writes you want DynamoDb to let connected nan array per second.

When you tally nan codification above, you should get output that looks for illustration this:

Screenshot showing console output for create array cognition successful DynamoDB

If you cheque your DynamoDB tables dashboard successful nan web console, you will spot nan array either still being provisioned aliases pinch a position of active already.

Always see your exertion needs erstwhile specifying nan ReadCapacityUnits and WriteCapacityUnits because an inappropriate worth tin lead to capacity problems aliases precocious billing costs connected your account.

Once you’re judge nan array is already active, you tin execute CRUD operations connected it.

The pursuing are immoderate codification examples that show you really to constitute and publication information from nan Customer table.

  1. Add information to nan table. To constitute information to a table, you request nan client’s putItem method. The codification beneath adds a caller customer to nan Customer array successful 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": "[email protected]" },
        Age: { "N": "18"},
        Country: { "S": "Nigeria" }
    }

    createCustomer(customerData)

    The params entity contains nan TableName which is nan array you’re penning to, and nan Item section which contains nan information you’re adding pinch their circumstantial types. Notice nan caller fields that weren’t successful nan array initially, this is really DynamoDB useful flexibly. You tin position nan information successful your database successful your console for illustration this:
    Screenshot of AWS DynamoDB console showing array data
  2. Read information from nan table. DynamoDB allows you to publication information successful various ways. The SDK’s scan usability sounds nan full table, while getItem sounds only circumstantial data. For instance, nan codification beneath gets each customers: const getAllCustomers = async () => {
        const params = {
            TableName: "Customer"
        }

        const customers = await client.scan(params)
        console.log(customers)
    }

    While nan pursuing codification gets nan personification by nan email value: const getCustomerByEmail = async (email) => {
        const params = {
            TableName: "Customer",
            Key: {
                Email: { "S": email }
            }
        }

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

    getCustomerByEmail("[email protected]")

  3. Update information successful nan table. To update existing information successful a table, usage nan SDK’s updateItem function. The pursuing codification demonstrates really to update a circumstantial record:  const updateCustomerLocation = async (email, age) => {
         const params = {
             TableName: "Customer",
             Key: {
                 Email: { "S": email }
             },
             UpdateExpression: "SET Age = :newAge",
             ExpressionAttributeValues: {
                 ':newAge': { "N": property }
             },
             ReturnValues: "ALL_NEW"
         }

         const updatedCustomer = await client.updateItem(params)
         console.log(updatedCustomer.Attributes)
     }

    You tin besides take to make your usability move by building update expressions from your update data. DynamoDB’s elasticity allows you to grip each cognition according to your needs.
  4. Delete information from nan table. To delete a grounds from DynamoDB, you request nan deleteItem usability and nan cardinal of nan peculiar record. Here’s really to instrumentality 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("[email protected]")

Building Efficient Applications With DynamoDB

Amazon Web Services continues to thrive. It provides an accessible level you tin usage to present efficient, unafraid integer solutions. DynamoDB is nan cleanable prime if you’re looking for a database to get moving without worrying astir infrastructure aliases security.

You are now equipped pinch each you request to get started pinch DynamoDB successful Node.js, and you tin confidently take DynamoDB for your adjacent Node.js application.

Source Tutorials
Tutorials