Node.js – Create Database in MongoDB

We can create a Database in MongoDB from Node.js program using mongodb module.

In this Node.js Tutorial, we shall learn to Create Database in MongoDB from Node.js Application with an example.

Steps to Create Database in MongoDB via Node.js

Following is a step by step guide with an example to create a database in MongoDB from Node.js Application.

Step 1: Start MongoDB Service.

Run the following command to start MongoDB Service.

sudo service mongod start

Step 2: Install mongodb package using npm.

Refer Node.js MongoDB Tutorial to install mongodb package.

Step 3: Get the base URL to MongoDB Service.

A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell.

arjun@nodejs:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings: 
2017-10-29T18:15:36.110+0530 I STORAGE  [initandlisten] 

While the Mongo Shell starts up, it echoes back the base url of MongoDB.

mongodb://127.0.0.1:27017

Step 4: Prepare the complete URL.

Append the Database name you want to create (say newdb), to the base URL.

mongodb://127.0.0.1:27017/newdb

Step 5: Create a MongoClient.

</>
Copy
var MongoClient = require('mongodb').MongoClient;

Step 6: Make connection from MongoClient to the MongoDB Server with the help of URL.

Note: In MongoDB, creating Database is an implicit process.

</>
Copy
MongoClient.connect(url, <callback_function>);

Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.

If the connection is successful, the db object points to the newly created database newdb.

Example 1 – Create MongoDB Database from Node.js

In this example, we will create a new database named newdb from Node.js program.

node-js-mongodb-create-database.js

</>
Copy
// newdb is the new database we create
var url = "mongodb://localhost:27017/newdb";

// create a client to mongodb
var MongoClient = require('mongodb').MongoClient;

// make client connect to mongo service
MongoClient.connect(url, function(err, db) {
	if (err) throw err;
	console.log("Database created!");
	// print database name
	console.log("db object points to the database : "+ db.databaseName);
	// after completing all the operations with db, close it.
	db.close();
});

Output

arjun@tutorialkart:~/workspace/nodejs/mongodb$ node node-js-mongodb-create-database.js 
Database created!
db object points to the database : newdb

Reference

MongoDB Tutorial – Learn MongoDB from basics with Examples.

Conclusion :

In this Node.js MongoDB tutorial : Node.js – Create Database in MongoDB, we have learnt to create a database from Node.js Application using mongodb package. In our next tutorial – Node.js MongoDB Drop Database, we shall learn to delete the database.