Node.js Create Collection in MongoDB using createCollection()

You can create a MongoDB collection from a Node.js application by connecting with the official MongoDB driver and calling db.createCollection() on the database object.

In this Node.js Tutorial, we shall learn how to create a collection in a MongoDB database from a Node.js application. The tutorial includes the original callback-style example and an updated async/await example that matches the way the current MongoDB Node.js driver is commonly used.

A MongoDB collection is a group of documents inside a database. It is similar to a table in a relational database, but the documents in a collection can have flexible fields. MongoDB can also create a collection automatically when you first insert data into a collection name that does not already exist. Use createCollection() when you want to create the collection explicitly, or when you need options such as schema validation, capped collection settings, time series options, or other collection-level configuration.

Prerequisites for creating a MongoDB collection from Node.js

Before running the examples, make sure that you have the following installed and available:

  • Node.js and npm on your machine.
  • A running MongoDB server, either local MongoDB or a MongoDB Atlas cluster.
  • The official mongodb package installed in your Node.js project.
  • A database name, such as newdb, and a collection name, such as users.

Install the MongoDB driver in your Node.js project with npm.

</>
Copy
npm install mongodb

Steps to Create Collection in MongoDB via Node.js

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

Step 1: Start MongoDB Service.

Run the following command to start MongoDB Service.

sudo service mongod start

On newer Linux systems, the equivalent command may be sudo systemctl start mongod. The command above is kept unchanged from the original tutorial example.

Step 2: 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

In current MongoDB installations, the shell command is usually mongosh. For a local server, the base connection string is still commonly mongodb://127.0.0.1:27017 or mongodb://localhost:27017.

Step 3: Prepare the complete URL.

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

mongodb://127.0.0.1:27017/newdb

With the current MongoDB Node.js driver, you can also connect to the server first and then select the database using client.db("newdb"). This keeps the database name clear in code and works well when the same client may access more than one database.

Step 4: Create a MongoClient.

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

For modern CommonJS code, you will usually import MongoClient with destructuring.

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

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

</>
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 database, newdb.

The current driver is commonly used with async and await. In that style, you create a client, connect to MongoDB, select a database, and close the client in a finally block.

</>
Copy
const client = new MongoClient("mongodb://127.0.0.1:27017");

await client.connect();
const db = client.db("newdb");

Step 6: Create a MongoDB Collection in the database.

Following is the syntax of createCollection() method used to create collection in MongoDB from Node.js.

</>
Copy
db.createCollection(<collection_name>, <callback_function>)
collection_nameName of the new MongoDB Collection, that we would like to create
callback_functionThis Node.js Callback Function is called after Node has tried creating a collection, and ready with the result. The callback function receives error and result object as arguments.

In async/await style, the same operation is usually written as follows.

</>
Copy
await db.createCollection("users");

You may also pass collection options as the second argument.

</>
Copy
await db.createCollection("users", collectionOptions);

Updated example: create the users collection with async/await

The following example connects to a local MongoDB server, selects the newdb database, and creates a collection named users. This is the recommended style for a new Node.js script because it keeps connection handling easy to read.

node-js-mongodb-create-collection-async.js

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

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

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

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

    console.log(`Created collection: ${collection.collectionName}`);
  } catch (error) {
    if (error.codeName === "NamespaceExists") {
      console.log("Collection already exists.");
    } else {
      throw error;
    }
  } finally {
    await client.close();
  }
}

createUsersCollection().catch(console.error);

Output when the collection is created

Created collection: users

Output when the collection name already exists

Collection already exists.

Example 1 – Create Collection in MongoDB via Node.js

In this example, we will connect to a MongoDB Database and create a collection named “users”. This is the original callback-style example. It is useful for understanding older Node.js MongoDB tutorials, but new code should prefer the async/await version shown above.

node-js-mongodb-create-collection.js

</>
Copy
// we create 'users' collection in newdb database
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;
	// db pointing to newdb
	console.log("Switched to "+db.databaseName+" database");
	// create 'users' collection in newdb database
	db.createCollection("users", function(err, result) {
		if (err) throw err;
		console.log("Collection is created!");
		// close the connection to db when you are done with it
		db.close();
	});
});

Output

arjun@tutorialkart:~/workspace/nodejs/mongodb$ node node-js-mongodb-create-collection.js 
Switched to newdb database
Collection is created!

Create a MongoDB collection with schema validation in Node.js

One common reason to explicitly create a MongoDB collection is to add schema validation. The following Node.js example creates a users collection where name and email are required string fields.

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

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

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

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

    await db.createCollection("users", {
      validator: {
        $jsonSchema: {
          bsonType: "object",
          required: ["name", "email"],
          properties: {
            name: {
              bsonType: "string",
              description: "name must be a string and is required"
            },
            email: {
              bsonType: "string",
              description: "email must be a string and is required"
            }
          }
        }
      },
      validationAction: "error"
    });

    console.log("Validated users collection is created.");
  } finally {
    await client.close();
  }
}

createValidatedUsersCollection().catch(console.error);

This validation does not replace application-level checks, but it helps the database reject documents that do not match the minimum structure expected for the collection.

Auto create a MongoDB collection when inserting from Node.js

You do not always need to call createCollection(). If you insert a document into a collection that does not exist, MongoDB can create that collection implicitly. This is useful for simple collections where you do not need validation or special collection options.

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

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

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

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

    await db.collection("activity_logs").insertOne({
      message: "Collection created by first insert",
      createdAt: new Date()
    });

    console.log("Document inserted into activity_logs.");
  } finally {
    await client.close();
  }
}

insertIntoNewCollection().catch(console.error);

Output

Document inserted into activity_logs.

Choose explicit creation with createCollection() when you need collection options. Choose implicit creation when a normal collection with default settings is enough.

Check whether the users collection exists after creating it

After creating a collection, you can verify it with listCollections(). This is helpful in scripts where you want to avoid trying to create the same collection repeatedly.

</>
Copy
const exists = await db.listCollections({ name: "users" }).hasNext();

if (exists) {
  console.log("users collection exists");
} else {
  console.log("users collection does not exist");
}

You can use this check before calling createCollection(), or you can handle the duplicate collection error as shown in the async/await example.

MongoDB connection string for local MongoDB and Atlas

For a local MongoDB server, the connection string usually points to port 27017.

</>
Copy
mongodb://127.0.0.1:27017

For MongoDB Atlas, use the connection string provided by Atlas. It usually has this form. Replace the placeholders with your real username, password, cluster host, and database settings.

</>
Copy
mongodb+srv://<username>:<password>@<cluster-host>/

Do not hard-code production passwords directly in source files. Use environment variables or a secure configuration method for real applications.

Common Node.js MongoDB createCollection errors and fixes

Error or issueLikely reasonHow to fix it
NamespaceExistsThe collection name is already present in the database.Check with listCollections(), choose another name, or handle the error safely.
ECONNREFUSEDThe MongoDB server is not running, or the host and port are wrong.Start MongoDB and confirm the connection string.
Authentication failedThe username, password, database, or authentication source is incorrect.Use the correct MongoDB user credentials and connection string.
Collection created in the wrong databaseThe script selected a different database name than expected.Check the value passed to client.db("newdb") or the database name in the URL.
Script exits before the operation completesAsynchronous code was not awaited correctly.Use await with createCollection() and close the client in finally.

Node.js MongoDB collection checklist before running the script

  • Confirm that MongoDB is running locally or that your Atlas cluster is reachable.
  • Use the correct database name in client.db("newdb").
  • Use a collection name that follows your application naming convention, such as users or orders.
  • Decide whether you need explicit createCollection() options or automatic collection creation by first insert.
  • Handle the case where the collection already exists.
  • Close the MongoDB client after the create collection operation completes.

Frequently asked questions about creating MongoDB collections in Node.js

How do I create a collection in MongoDB using Node.js?

Connect to MongoDB with MongoClient, select the database with client.db("databaseName"), and call await db.createCollection("collectionName"). For example, await db.createCollection("users") creates a collection named users.

Do I have to create a MongoDB collection before inserting documents?

No. MongoDB can create a normal collection automatically when you insert the first document into a collection name that does not exist. However, use createCollection() when you need schema validation, capped collection settings, time series settings, or other collection options.

Why does createCollection() return NamespaceExists in Node.js?

NamespaceExists means that the collection already exists in that database. Check the existing collections with listCollections(), use another collection name, or catch the error and continue when an existing collection is acceptable.

How can I check if a MongoDB collection exists from Node.js?

Use await db.listCollections({ name: "users" }).hasNext(). It returns true when the collection exists and false when it does not.

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

Both approaches can work. In new Node.js code, it is often clearer to connect with the server URL, such as mongodb://127.0.0.1:27017, and then select the database with client.db("newdb").

Node.js MongoDB collection references

For more details, see the official MongoDB Node.js driver guide on databases and collections, the MongoDB manual entry for db.createCollection(), and the MongoDB manual overview of databases and collections.

MongoDB Tutorial – Learn MongoDB from basics with Examples.

Node.js create collection in MongoDB recap

In this Node.js MongoDB tutorial, we learnt how to create a collection in a MongoDB database from a Node.js application using the mongodb package. For new code, prefer the async/await pattern with MongoClient, client.db(), and await db.createCollection("users"). For simple collections, MongoDB can also create the collection automatically when you insert the first document. In our next tutorial – Node.js MongoDB Delete Collection, we shall learn to delete the collection, or you may continue to Node.js Insert Document(s) to MongoDB Collection.