
Node.js is a Javascript runtime environment that allows you to build highly scalable applications with support for popular relational database systems such as MySQL. You can integrate a Vultr Managed Database for MySQL with your Node.js application to make it highly available and scalable.
Follow the steps in this guide to use a Vultr Managed Database for MySQL with Node.js. You will create a sample Node.js project, and use the mysql2 library to connect to the deployed database. In addition, execute queries to view the database data using your application.
Before you begin, make sure you:
Create a new project directory
Switch to the new project directory.
Using npm, initialize your project
The above command creates a new package.json file in the directory that contains all important information about the project including the metadata and project dependencies
Install the project dependencies
The above command installs the mysql2 package that allows Node.js application to interact with MySQL databases. The dotenv package loads environment variables such as database connections from a .env file to your process.env object.
View the package.json file and verify that all dependency packages are available to the project
Your output should look like the one below with different version numbers:
Create the main project index.js file
Using a text editor such as Nano, create a new .env file to store the database information values
Add the following variables to the file. Replace the example values with your actual Vultr Managed Database for MySQL details
Save and close the file.
To connect your Node.js application to the MySQL database, use the mysql2 library to use your .env file details as described in the steps below.
Open and edit the index.js file
Add the following code to the file
Import the project dependencies
The above code imports mysql2 module, and the dotenv module that reads the contents of your .env file, then forwards the contents to process.env.
Create a new object to store database connection details from the process.env variable.
Create a database connection connectToDB() method
In the above code, the createPool() connection method creates a pool of connections to the database. The mysql2 module supports the following two methods:
createConnection(): Creates one-time connection to execute queries. One connection can only handle one query at a time. The Next time a query executes, the application re-establishes a connection to the database again
createPool(): Creates a pool of connections to the database. Connection pooling enhances the performance of executing the commands on a database. Instead of establishing a new connection every time the application only executes a query and gets a connection from the pool
Further, pool.promise() wraps the pool object into a promise-based version, and provides a version of the pool that returns promises. This makes it possible to use the async/await syntax for cleaner, and more readable asynchronous code
Create the main() method to call the connectToDB() function with a Connected to Database result when successful
Call the main() method at the end of the file
Save and close the file
Your complete index.js should look like the one below:
The above index.js file connects your Node.js application to the deployed MySQL database on Vultr and assigns the promise-based pool to the db variable which supports CRUD operations.
Run the index.js file to start the Node.js application
Output:
To test your Node.js application functionality, create a new table in the connected database and perform CRUD operations using SQL queries as described in the steps below.
Open and edit the index.js file
Edit the connectToDB() method before return poolPromise;, and include a query that creates a new posts table using the CREATE TABLE IF NOT EXISTS SQL statement
Save and close the file.
The above code creates a new MySQL table with the following columns:
id: Automatically increments every new record with unique values using it's Primary Keytitle and body columns accept all characters (VARCHAR) and can store up to 255 charactersauthor: Supports all characters with up to 255 characters The const [allPosts, fields] = await poolPromise.query('SELECT * FROM posts;') query selects all records from the posts table. The query method returns an array where the first element is an array of rows from the query (assigned to allPosts), and the second element is an array of field metadata (assigned to fields).
Run the application
Your output should look like the one below:
Press Ctrl + C to stop the application
Edit the index.js file
Add a new createNewPost() method to that inserts a new post into the posts table
Call createNewPost() within the main() method along with some dummy data to create a new post
Save and close the file.
Run the application
Your output should look like the one below:
Press Ctrl + C to stop the application
Edit the application file
Create a new getPostById() method to fetch the data of a single post
Within the main() method, call getPostById() with some the postId to fetch post data
Run the application
Output:
Press Ctrl + C to stop the application
Edit the index.js file
Create a new updatePostById() method to update the posts table.
Within the main() method, call updatePostById() along with an some existing post id and the updated data. For example:
Run the application
Output:
Press Ctrl + C to stop the application
Edit the index.js application file
Create a new deletePostById() method to delete a post by ID
In the main() method, call deletePostById() with some the postId to delete. For example, delete the post with ID 2
Run the application
Output:
Press Ctrl + C to stop the application
You have integrated a Vultr Managed Database for MySQL with your Node.js application using the mysql2 library. Using the integration, you can create efficient and scalable backend solutions that meet the demands of modern applications. For more information on how to use the mysql2 Node.js library, visit the documentation page.
To implement more solutions using your Vultr Managed Database for MySQL, visit the following resources:
0 Comments
Be the first to comment and share your perspective with the community.