English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File(FS)

NodeJS Other

Node.js Create Database in MongoDB

In this Node.js tutorial, we will learn how to create a database in MongoDB from a Node.js application through an example.

Example

Here is a step-by-step guide, along with an example that creates a database in MongoDB from a Node.js application.

Start the MongoDB service. Run the following command to start the MongoDB service

 sudo service mongod start

Install the mongodb package using npm.
Get the basic URL of the MongoDB service. To understand the basic URL of the MongoDB service, a simple trick is to open the terminal and run the Mongo Shell.

Terminal-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]
When the Mongo Shell starts, it echoes the basic URL of MongoDB. 
mongodb://127.0.0.1:27017

Prepare a complete URL. Append the name of the database to be created (for example, newdb) to the basic URL.

mongodb://127.0.0.1:27017/newdb

Create a MongoClient.

var MongoClient = require('mongodb').MongoClient;

Connect to the MongoDB server from MongoClient with the help of the URL.

MongoClient.connect(url, <callback_function>);

Once the MongoClient attempts to establish a connection, the callback function will receive the error and db object as parameters.
If the connection is successful, the db object points to the newly created database newdb.

Sample Node.js Program

// newdb is the new database we created
var url = "mongodb://localhost:27017/newdb"; 
 
// Create a client to mongodb
var MongoClient = require('mongodb').MongoClient; 
 
// Make the client connect to the mongo service
MongoClient.connect(url, function(err, db) { 
    if (err) throw err; 
    console.log("Database created!"); 
    // Print the database name
    console.log("db object points to the database: ");+ db.databaseName); 
    // Close the db after completing all operations with it.
    db.close(); 
 });

Output Result

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

Conclusion:

In this Node.js MongoDB tutorial:  Node.js – Creating a Database in MongoDBWe learned how to create a database from a Node.js Application using the mongodb package. In our next tutorial – Node.js MongoDB Drop Database, we will learn how to delete a database.