Database integration in Express

Ranjul Arumadi
Last Updated: May 13, 2022


Express is a fast web framework for Node.js upholding minimalism.  It is a web application server framework used by developers to develop single, multi, or hybrid web applications. It is considered a standard server framework for node.js by many developers. 


Database integration in Express refers to the ability of Express to connect easily with databases like MySQL, MongoDB, Cassandra, etc. It is pretty easy to do database integration in Express as we only have to load the appropriate Node.js drivers of the database in our application.


A note on npm

Npm is a package manager for the JavaScript(JS) programming language. This blog shows that installing drivers for database integration in Express is achieved using the npm package manager. 


To check if you have npm on your computer, you can run the following command.

npm -v


If it's not present, you will receive an error like this:




It is better that you use a Node version manager like nvm to install Node.js and npm. It is not recommended to use a Node installer since the Node installation process installs npm in a directory with local permissions and can cause permissions errors when you run npm packages globally.


You can update your npm by running the following command:

npm install -g npm


Check out this blog on npm to learn more about it.

Database integration in Express.js

Let us look at how we can integrate a database in a server working upon the Express.js framework. The steps can be divided as creating the application, running the server and finally integrating the database.


Step 1: Create an Express Application 

Here we will create an Express application because all of our work will be going to execute inside Express. 


Running the following command in your terminal gets you to start a node app and install Express.

npm init
npm install express


Now create an empty .js file (let’s name it Ninja.js).

This is how your folder would look like now.

Folder structure


Now let's write Express code in our Ninja.js file.



// Importing the express module
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, (error) =>{
console.log("Server is Running "
+ "| App listening on port: "+ port)
console.log("Error occurred, cannot start the server", error);


Step 2: Running the server

Now run the server by giving the following command in your terminal.



node Ninja.js




Step 3: Integrating with database

There are a lot of databases available to integrate with Express. The choice depends on the requirements of the project you are working on. For now, let us choose MySQL and see how we can integrate it with Express.


Integrating with a database can be divided into 3 steps.


Step 1: Downloading MySQL driver for the Express application

Run the following command to download the driver.

npm install mysql


Step 2: Installing MySQL locally

To use MySQL, you should have it downloaded locally. You can visit their official website to download them. 


Step 3: Integrating with Express

For this, edit the Ninja.js file and insert the following code.



// Importing the express module
const express = require('express');
const app = express();
const port = 3000;

// Create a connection to the database
const mysql = require('mysql');
const PORT = 4000;
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: "test" 
// Open the MySQL connection
connection.connect(error => {
if (error){
console.log("A error has been occurred "
+ "while connecting to database."); 
throw error;
// If Everything goes correct, Then start Express Server
app.listen(PORT, ()=>{
console.log("Database connection is Ready and "
+ "Server is Listening on Port ", PORT);


Save the file. Start your web server and once again run the following command.

node Ninja.js


If there are no errors present, then you should get the following output..



Integrating with popular databases

Database integration in Express refers to connecting Express with databases like MySQL, MongoDB, Cassandra etc. It is quite easy to do database integration in Express as we only have to load the appropriate Node.js drivers of the database in our application. Let us see how we can install drivers of various databases to do database integration in Express and example codes for the same.


MongoDB is a source-available cross-platform document-oriented database program. It uses JSON-like documents.



$ npm install mongodb



const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://'
const dbName = 'CodingNinjas'

const db

MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
 if (err) return console.log(err)

 // Storing a reference to the database so you can use it later
 db = client.db(dbName)
 console.log(`Connected MongoDB: ${url}`)
 console.log(`Database: ${dbName}`)


PostgreSQL is a free and open-source relational database management system focusing on extensibility and SQL compliance.



$ npm install pg-promise


var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";
var client = new pg.Client(conString);


Apache Cassandra is a free and open-source, NoSQL database management system designed to handle very large amounts of data.



$ npm install cassandra-driver



var cassandraDB = require('cassandra-driver')
var client = new cassandraDB.Client({ contactPoints: ['localhost'] })
client.execute('select key from system.local', function (err, result) {
 if (err) throw err


Elasticsearch is a search engine based on the Lucene library. 



$ npm install elasticsearch



var ES = require('elasticsearch')
var client = ES.Client({
 host: 'localhost:9200'


SQLite is a relational database management system contained in a C library.



$ npm install sqlite3



var SQLite3 = require('sqlite3').verbose()
var db = new SQLite3.Database(':memory:')
// Enter your code here
// Close connection after use

SQL Server

Microsoft SQL Server is a relational database management system made by Microsoft.



$ npm install tedious



var Connection = require('tedious').Connection
var Request = require('tedious').Request
var config = {
 server: 'localhost',
 authentication: {
   type: 'default',
   options: {
     userName: 'username', // Update this value
     password: 'pwd' // Update this value
var connection = new Connection(config)


Redis is an in-memory database that persists on a disk. 



$ npm install redis



var redis = require('redis')
var client = redis.createClient()
client.on('error', function (err) {
 console.log('Error ' + err)
// Enter your code here

// Close connection after use


Oracle Database is a multi-model database management system produced and marketed by Oracle Corporation.



$ npm install oracledb



const oracleDatabase = require('oracledb')
const config = {
 user: 'your-username',
 password: 'your-password',
 connectString: 'localhost:1521/orcl'

// Create connection
connection = oracledb.getConnection(config)

// Close connection


Neo4j is a graph database management system. It was developed by Neo4j, Inc.



$ npm install neo4j-driver



var neo4j = require('neo4j-driver')
var driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
var session = driver.session()


LevelDB is an open-source on-disk key-value store.



$ npm install level levelup leveldown



var levelup = require('levelup')
var database = levelup('./mydb')


Apache CouchDB is an open-source document-oriented NoSQL database.



$ npm install nano



var couch = require('nano')('http://localhost:5984')
// Creating a database named books
var books = couch.db.use('books')


Couchbase is an open-source, distributed multi-model NoSQL document-oriented database.



$ npm install couchbase



var couchbase = require('couchbase')
var bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName')

Frequently Asked Questions

  1. How can I do database integration in Express?

It is easy to do database integration in Express. You only have to load the appropriate Node.js drivers of the database in your application.

2. Can I use some other package managers other than npm to install the drivers?

                     Yes, you can use other package managers. Yarn is one popular choice after npm.


Key Takeaways

We have looked into database integration in Express and understood that it refers to connecting Express with databases like MySQL, MongoDB, Cassandra, etc. We also saw that It is quite easy to do database integration in Express as we only have to load the appropriate Node.js drivers of the database in our application. 


If you enjoyed reading this article about Database integration in Express, check out Free JavaScript Tutorial By Coding Ninjas and 10 Best JavaScript Certifications In 2021.

Was this article helpful ?
1 upvote


No comments yet

Be the first to share what you think