Tuesday, April 28, 2020

Node.js MongoDB installation and creating Database Connection

Node.js MongoDB 


node mongodb database


Installation and creating Database Connection


MongoDB


MongoDB is a very popular and leading NoSQL database application. It is cross-platform and has a document-oriented design which is used to store the data in JSON-like documents with Schema.

First, we need to have access to the database to work with MongoDB. MongoDB is freely available and it can be downloaded from, https://www.mongodb.com.

Choose the correct version of MongoDB according to your Operating system and architecture and install it to your machine.

Install the MongoDB Driver


To install the MongoDB driver, just open the Node.js command prompt and execute the install command.

C:\Users\Your Name>npm install mongodb  

This driver provides both callback-based and Promise-based interaction with MongoDB. This driver provides a high-level API on top of the mongodb-core that is available for the developers to use.

Once the driver is downloaded and installed, Node.js can use this module to access and manipulate the MongoDB databases.

var mongo = require('mongodb');    


Creating a Database


To create a database in MongoDB, First, we need to create the MongoClient object, and then call the connect() method on this object. We need to specify a connection URL with the IP address (localhost in case if the database is available on the local machine), port number, and the database name.

    //including the MongoDB Driver
    const MongoClient = require('mongodb').MongoClient;
    const url = "mongodb://localhost:27017/testdb";

    MongoClient.connect(url, function(error, database) {
      if (error) throw error;
      console.log("Successfully, created Database!");
      database.close();
    });
/*
Output:
Successfully, created Database!
*/


However, in MongoDB, a database is actually never created until it has some content.

The database is only created when a collection (table) is created in it with at least one document (record).