Create a Collection in MongoDb using Node.js


What do we intend to make ?

In this Chapter , we will create a collection name "details" within our database name "demo_db" in the NoSql , Document oriented database MongoDb using the Server Side platform Node.js

Let's Start !

Step - 1 : Including Packages
We will start by requiring the require package. We are using the following package in our application :

		        

var mongo = require('mongodb');
                
	            

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 collection
createCollection() is an inbuilt method used to Creates a new collection or view.

		        
//create_collection_mongo_nodejs.js

mongo.connect(new_db , (error , db) => {
	if (error){
		throw error;
	}
	
	
	//CREATING A COLLECTION IN MONGODB USING NODE.JS
	db.createCollection("details" , (err , collection) => {
		if(err) throw err;
		
		console.log("Details collection created successfully");
		
	});
});


                
	            

You can run the above code using the following command :

		        

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

				
	            

The output of the above code is :

		        

D:\nj-learn-mongo>node create_collection_mongo_nodejs.js
Details collection created successfully