Create a Database in MongoDb using Node.js


What do we intend to make ?

In this Chapter , we will create database demo_db in the NoSql , Document oriented database MongoDb using Node.js

Let's Start !

Step - 1 : Installing Packages
We will start by installing all the required packages from npm. We are using the following package in our application :

		        

var mongo = require('mongodb');
                
	            

We can install it using the following command:


		        
npm install mongodb --save
                
	            

Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.

		        

var new_db = "mongodb://localhost:27017/demo_db"



                
	            

  • demo_db is the name of the database. You can change it as per your wish.
  • 27017 is the port where our mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step - 3 : Create the database
Connect() is an inbuilt method used to is an inbuilt method used to Creates a connection to a MongoDB instance and returns the reference to the database. It instantiates a new connection to the MongoDB instance running on the localhost interface and returns a reference to demo_db

		        
//create_database_mongo_nodejs.js

mongo.connect(new_db ,(error , db) => {
	if (error){
		throw error;
	}
	console.log("Database demo_db created successfully");
	//To close the connection
	db.close();
});

                
	            

You can run the above code using the following command :

		        

D:\nj-learn-mongo>node create_database_mongo_nodejs.js
				
	            

The output of the above code is :

		        

D:\nj-learn-mongo>node create_database_mongo_nodejs.js
Database demo_db created successfully