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.

In MongoDB, a database is created implicitly. This means that MongoDB does not require a separate CREATE DATABASE command. When a Node.js application connects to a database name and then creates a collection or inserts data, MongoDB creates the database if it does not already exist.

For practical use, it is better to think of the process as selecting a database name first, then creating a collection or writing a document to make the database appear in MongoDB.

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

The example above connects to the database name newdb. In many MongoDB setups, the database may not be listed until at least one collection or document is created in it. Therefore, for a real application, connect to the database and then create a collection or insert a document.

Create MongoDB Database in Node.js by Creating a Collection

The following example uses the current Node.js driver style with async and await. It connects to MongoDB, selects the database name newdb, and creates a collection named customers. This action makes the database exist in MongoDB if it was not already present.

create-database-with-collection.js

</>
Copy
const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function createDatabase() {
  try {
    await client.connect();

    const db = client.db("newdb");
    await db.createCollection("customers");

    console.log("Database selected:", db.databaseName);
    console.log("Collection created: customers");
  } catch (error) {
    console.error("Error creating database:", error.message);
  } finally {
    await client.close();
  }
}

createDatabase();

Run the Node.js file from the terminal.

</>
Copy
node create-database-with-collection.js

Expected output:

Database selected: newdb
Collection created: customers

Create MongoDB Database in Node.js by Inserting a Document

Another common way to create a MongoDB database from Node.js is to insert the first document into a collection. If the database and collection do not already exist, MongoDB creates them during the insert operation.

create-database-with-insert.js

</>
Copy
const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function createDatabaseWithDocument() {
  try {
    await client.connect();

    const db = client.db("newdb");
    const collection = db.collection("customers");

    const result = await collection.insertOne({
      name: "Ravi Kumar",
      city: "Hyderabad"
    });

    console.log("Database selected:", db.databaseName);
    console.log("Inserted document id:", result.insertedId);
  } catch (error) {
    console.error("Insert failed:", error.message);
  } finally {
    await client.close();
  }
}

createDatabaseWithDocument();

This example is closer to normal application code because most databases are created as part of the first write operation. The database name is selected using client.db("newdb"), and the collection is selected using db.collection("customers").

Check Whether the MongoDB Database Was Created

After running a program that creates a collection or inserts a document, open the MongoDB shell or mongosh and list the databases.

</>
Copy
mongosh

Then run the following command inside the shell.

</>
Copy
show dbs

If newdb contains a collection or document, it should appear in the database list. If you only connected to the database name and closed the connection without writing anything, the database may not appear.

MongoDB Connection URL for Localhost and Database Name

The connection URL tells the Node.js driver where MongoDB is running. For a local MongoDB server, the base URL is commonly mongodb://127.0.0.1:27017 or mongodb://localhost:27017.

Connection URLMeaning
mongodb://127.0.0.1:27017Connect to the local MongoDB server without selecting a database in the URL.
mongodb://127.0.0.1:27017/newdbConnect to the local MongoDB server and select newdb as the database name.
mongodb://localhost:27017/newdbSame idea as above, using localhost instead of 127.0.0.1.

When using a remote MongoDB server or a managed MongoDB service, the URL usually includes authentication details and host information. Keep that connection string outside the source code by using environment variables in production applications.

Common Errors While Creating MongoDB Database from Node.js

The following issues are common when creating a MongoDB database from a Node.js application.

Error or symptomPossible reasonWhat to check
ECONNREFUSEDMongoDB server is not running or the port is wrong.Start MongoDB and verify the host and port in the connection URL.
Database does not appear in show dbsNo collection or document has been created yet.Create a collection or insert at least one document.
Authentication failedUsername, password, or authentication database is incorrect.Check the connection string and user permissions.
MongoServerError: Collection already existsThe collection name already exists when using createCollection().Use an existing collection with db.collection() or choose a new collection name.

Node.js MongoDB Database Creation Checklist

  • MongoDB service is running before the Node.js program is executed.
  • The mongodb npm package is installed in the project.
  • The connection URL contains the correct host, port, and database name.
  • The code closes the MongoDB client after the operation is complete.
  • The database is verified only after creating a collection or inserting a document.
  • Connection strings with credentials are not hard-coded in production code.

Reference

MongoDB Tutorial – Learn MongoDB from basics with Examples.

For more Node.js and MongoDB examples, refer to Node.js MongoDB Tutorial.

FAQs on Creating MongoDB Database in Node.js

Can Node.js create a MongoDB database automatically?

Yes. A Node.js application can create a MongoDB database implicitly by connecting to a database name and then creating a collection or inserting a document into it.

Why is my MongoDB database not shown after connecting from Node.js?

MongoDB may not show a database that has no collections or documents. After connecting to the database name, create a collection or insert a document, and then check the database list again.

Which npm package is used to connect Node.js with MongoDB?

The official MongoDB Node.js driver is installed using the mongodb npm package. It provides MongoClient, which is used to connect to MongoDB from Node.js.

Should I put the MongoDB database name in the URL or in client.db()?

Both approaches can be used. You may include the database name in the connection URL, such as mongodb://127.0.0.1:27017/newdb, or connect to the server URL and select the database with client.db("newdb").

Do I need to create a MongoDB collection before inserting data from Node.js?

No. You can select a collection with db.collection("collectionName") and insert a document. MongoDB creates the collection during the insert if it does not already exist.

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.

The main point to remember is that MongoDB creates databases implicitly. A Node.js program should connect to the required database name and then create a collection or insert a document so that the database is actually created and visible in MongoDB.