Connecting Databases in Node JS

 

    Every web server needs to store some data either in files or in RAM. But there are drawbacks of each. RAM present in a system is very limited and costs more. Also it is volatile memory meaning that the data is lost when device switched off. 
Files on other hand have problem that reading and writing data is very time consuming process. Also to change some line of a file you would need to rewrite the whole file again and again. 

As a solution to efficient storages, databases were designed. Database is another system which writes data to your disk but not in the form of files. This way manipulation data is less CPU intensive with databases. 

This article aims to introduce you to the method of connecting various databases with your NodeJS app.

In any basic NodeJS application you will use all or any of the three following databases:
  • SQL (or Relational Databases) - MySQL, PostgreSQL etc.
  • NoSQL Database - MongoDB, DynamoDB etc
  • In-Memory Databases - Redis
Adding databases to your NodeJS application is very easy. We will look at some of the modules you can use for connecting databases.

P.S. before running the examples, make sure that your databases are running at their default ports. (MongoDB - 27017 , Redis - 6379, MySQL - 3306)

MongoDB
     The npm repository hosts some awesome mongodb connectors. One famous one is the mongoose library. We will be using this module in future articles. Install the mongoose module by doing

> npm install --save mongoose                                                                   

in your project root directory. 

Now open your server.js file and write the following code.

server.js

"use strict";

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');

var app = express();
let PORT = 3000;

function connectToDatabases(){
  mongoose.connect('mongodb://127.0.0.1/myDatabase', function(){
    console.log("Connected to MonogDB database myDatabase");
  });
}

connectToDatabases();

app.listen( PORT, function(){
    console.log("Server started listening on port: "+PORT);
});

Here we create the server normally as before and add another function connectToDatabases() which will initialize all the databases. Then we need to call the function. 
Mongoose module provides a method mongoose.connect() to connect to any mongodb database. It accepts the URL where the database is hosted and a callback function. The callback function is called after the connection is established.

On running this you should see something like:


Note that the database connection is completed after starting the server. This is due to the connection being established in background thread.
Now the connection is established is shared among the entire mongoose library. 

Here you connect to the URL:

mongodb://127.0.0.1/myDatabase                                                              

Here the mongodb:// protocol tells the server which port to look for mongodb. It is same as:

http://127.0.0.1:27017/myDatabase                                                            

Here we specify the port explicitly. myDatabase is the database name which we will use for storing data.

If you have enabled authentication on your database, then you can connect using:

http://username:password@127.0.0.1:27017/myDatabase                        

Mongoose is very popular and large module which will extensively be used in many apps. Hence the usage of mongoose library will be dealt with in next articles. 

Redis
Using redis is fairly simple as compared to MongoDB. We will use the redis module for NodeJS. Install it using:

> npm install --save redis                                                                          

You can connect to your redis instance of your site using the following in the server.js file:

"use strict";

const express = require('express');
const path = require('path');
const redis = require('redis');

var app = express();
let PORT = 3000;

function connectToDatabases(){
  let client = redis.createClient({host: 'http://127.0.0.1', port: 6379});
  client.on('connect', function(){
    console.log("Redis Connected");
  });
  client.auth("MyDatabasePassword");
  global.client = client;
}

connectToDatabases();

app.listen( PORT, function(){
    console.log("Server started listening on port: "+PORT);
});

We first require the redis module and connect to the database using redis.createClient() function in which we need to pass the host and port where the database is hosted. The connection object is stored in the client object which has an ‘connect’ event which is fired when connection is successful. 

If your database has a password, then you can login using client.auth() which accepts a password for authenticating the database.  The problem with this module is that for executing queries, we need the client object. Hence we make the client object a global object so that all the files can access it without the need to reconnect.

Querying using this module is very simple. Suppose you want to store a key value pair:


client.set(<key>, <string value>, function(err, reply){
  // err object is null of successful
  // reply contains the response from the datase
});

// For storing hset
client.hset(<key>, <set_key>, <value>, function(err, reply) {...});

To retrieve the values:
client.get(<key>, function(err, values){...});

There are many other function available at their official documentation. These methods are very simple to understand.

MySQL
The module for MySQL is very similar to the redis one. Install the module by using:

> npm install --save mysql                                                                                      

Write the following in server.js file:

"use strict";

const express = require('express');
const path = require('path');
const mysql = require('mysql');

var app = express();
let PORT = 3000;

function connectToDatabases(){
  let connection = mysql.createConnection({
    host: '127.0.0.1',
    user: <username>,
    password: <databasePassword>,
    database: 'myDatabase'
  });
  connection.connect();
  global.connection = connection;
}

connectToDatabases();

app.listen( PORT, function(){
    console.log("Server started listening on port: "+PORT);
});

As with redis, we create a connection object by passing the host, username, password and database name to the mysql library. Then make this connection object global.

To execute various queries on the database use:


connection.query("SELECT * FROM Person", function(err, results){ .. });

Results is a matrix containing the result in table form.

This is how you connect to various databases in NodeJS. There are connectors for other databases as well which you can find on npmjs. If you do not use connectors from npmjs, you would need to write C level database interfacing code and interact with it.

A detailed article on Mongoose will be covered in the next article.

No comments:
Write comments

Popular Posts