Mongodb-node.js Tutorial Series

Create Database in MongoDB using node.js

MongoDB-Nodejs tutorial | Perform mongodb operations using node.js


In this part of the mongodb operations using node.js tutorial series , we will create a database demo_db in MongoDb using Node.js

Let's Start !!
Step 1 - Installing Package

We will start by installing mongodb package from the node package manager npm as shown below

npm install mongodb --save


Include the installed package as shown below :
var mongo = require('mongodb');


Step-2 : Establish Connection

Establish a connection between the mongoDb database and our node.js app using the following :

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

  • demo_db is the name of the database. You can change it in accordance with your database name.
  • 27017 is the port where mongoDb is running.
  • Localhost i.e. is the local IP.

Step - 3 : Create the database

Connect() is an inbuilt method used to create 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:

var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db";

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

You can run the above code using the following command :
>node create-db.js
Database demo_db created successfully

What we learned

In this article we learned about

  1. Installing monogdb package from npm.
  2. Establishing a connection between mongodb database and node.js application.
  3. Create a database in mongodb using node.js