With the help of node.js, front-end developers can use the same programming language that is JavaScript just like back-end developers. This provides more cross-functional and Agile development of any web application or mobile application. Node js is widespread and it is very popular due to JavaScript being a very common language and it is highly recommended for development processes. Here, in this article, we’re discussing the use of the database with node js. Let’s read more to know about it.

Lately, NoSQL databases have escalated, and then almost declined in popularity. They often seem much easier to get started with than SQL databases because of the need of learning a new language and define your schema up-front not necessary. Some improvements in scalability vs more traditional SQL databases shown below.

  • An important aspect to keep in mind is that Facebook stores the vast majority of its data in a few MySQL servers. Unless its a big tech company like Google or Facebook, it is likely that Postgres or MySQL will scale to meet needs with lack of problems.
  • The thought which can be avoided about schema is NoSQL databases is also often flawed. It is often seen to end up with just as rigid a schema definition, except nobody has written down what that schema is.

Learning SQL is rational since it’s quite simple. If it’s for NoSQL database, MongoDB remains one of the most popular, but it is suggested that one must at least try using an SQL database first.

Database Integration

Some of the most popular Node.js modules are listed below:

Data Access in Node JS

Relational database or NoSQL database, Node.js supports all kinds of databases. However, NoSQL databases like MongoDb termed as the perfect fit with Node.js.

To access the database from Node.js:

  • Install drivers for the database you want to use.

The important relational databases and respective drivers are listed below:

Relational DatabasesDriverNPM Command
MS SQL Servermssqlnpm install mssql
Oracleoracledbnpm install oracledb
MySQLMySQLnpm install mysql
PostgreSQLpgnpm install pg
SQLitenode-sqlite3npm install node-sqlite

The important NoSQL databases and respective drives are listed below:

NoSQL DatabasesDriverNPM Command
MongoDBmongodbnpm install mongodb
Cassandracassandra-drivernpm install cassandra-driver
LevelDBleveldbnpm install level levelup leveldown
RavenDBravendbnpm install ravendb
Neo4jneo4jnpm install neo4j
Redisredisnpm install redis
CouchDBnanonpm install nano

Access SQL server in Node JS

For accessing MS SQL database:

  • Install drivers for it.
  • There are many drivers available for SQL server in NPM. Mssql driver is applied.

Install Driver:

Install the driver using npm command first, npm install mssql within the prompt. This adds mssql module folder in the node_modules folder in the Node.js application. For this, mssql v2.3.1 is selected (latest version). After installing the application driver, MS SQL server database can be used accordingly. Firstly, secure to a local SQLExpress database server and export the records from Student table in SchoolDB database as shown:

Database Table

Secondly, create server.js and write the following code.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
   
    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'sa',
        password: 'mypassword',
        server: 'localhost', 
        database: 'SchoolDB' 
    };

    // connect to your database
    sql.connect(config, function (err) {
    
        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();
           
        // query to the database and get the records
        request.query('select * from Student', function (err, recordset) {
            
            if (err) console.log(err)

            // send records as a response
            res.send(recordset);
            
        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

Mssql module has imported and called connect() method to connect with SchoolDB database. The config object which includes database information such as userName, password, database server, and database name has done. On the fortunate connection with the database, use sql.request object to execute the query to any database table and fetch the records.

Try to run using node server.js command and showcase the browser to the given URL which states an array of all the students from the Student table.

<em>http://localhost:5000</em>

Access MongoDB In Node JS

For accessing MongoDB database:

  • Install MongoDB drivers.
  • To install mongodb drivers using NPM, open command prompt and write the command below to install MongoDB driver.
  • It will obtain mongodb folder inside node_modules folder.
  • Begin the MongoDB server using the following command.

(Assumption: MongoDB database is at C:\MyNodeJSConsoleApp\MyMongoDB folder.)

For accessing MongoDB database:

  • Install MongoDB drivers.
  • To install mongodb drivers using NPM, open command prompt and write the command below to install MongoDB driver.
  • It will obtain mongodb folder inside node_modules folder.
    Begin the MongoDB server using the following command.
(Assumption: MongoDB database is at C:\MyNodeJSConsoleApp\MyMongoDB folder.)

In the above example, mongodb module imported (native drivers) and secured the reference of MongoClient object. Then MongoClient.connect() is used in order to attain the reference of the specified MongoDB database.

 mongodb://localhost:27017/MyDb 

The specified URL points to the local MongoDB database created in MyMongoDB folder. The connect() method returns the database reference if the stated database is already present, else a new database will be created.

Lastly, write insert/update or query the MongoDB database in the callback function of the connect() method present using the db parameter.

Conclusion

These are some of the best databases for using node.js.  You will need to have full command on node.js and MongoDB to integrate them and work together.

Categorized in: