MongoClient Create Collection in Node.js

Creating a MongoDB collection from Node.js gives an application a named place to store documents. A collection groups documents inside a database, and the MongoDB Node.js driver can create one.

This article shows how to create an empty collection and confirm its name with listCollections().

TL;DR: Create a MongoDB Collection with Node.js

Call createCollection() on a database handle when a collection must exist before its first document. MongoDB can also create one on the first insert.

  • Connect with MongoClient, then choose a database with client.db().
  • Use await database.createCollection(‘orders’) to create an empty collection.
  • Use listCollections() to confirm the name, and close the client when finished.

What Is a MongoDB Collection?

A MongoDB collection groups documents inside a database. Documents are BSON records with fields, and unlike a relational table, records in a collection do not need identical fields.

For an app, a collection is the place a database handle addresses when it reads or writes documents. The Node.js driver exposes that collection through the database handle.

A MongoDB URI identifies the deployment, while client.db(‘appdb’) chooses the database within that deployment.

ChoiceDriver callResult
Create before the first documentdatabase.createCollection(‘orders’)Creates an empty collection and accepts collection options
Create as data arrivesdatabase.collection(‘orders’).insertOne(document)First insert creates a missing collection and stores its first document

The Node.js database and collection guide documents both choices. Use explicit creation for a validator or when setup needs an empty collection before the first document arrives.

How to Create a MongoDB Collection with Node.js

Use the mongodb driver and an async function so connection cleanup runs on success or failure. The sample targets the local URI and creates appdb.orders.

Step 1: Add the MongoDB driver

Install the official driver in the project directory. npm init creates the package manifest, and npm install mongodb adds the driver version selected by the registry at install time.

npm init -y
npm install mongodb

Step 2: Connect and select a database

Save this as create_collection.js, then replace the URI with your deployment’s connection string when MongoDB does not run locally. client.db(‘appdb’) selects the database handle.

Avoid committing credentials. The sample reads MONGODB_URI from the process environment. This lets development and deployment use different server addresses without changing the program.

The driver can connect lazily, but this example calls connect() first so a server-selection error appears before collection work.

For a hosted deployment, use its assigned URI. MongoDB’s MongoClient guide explains connection strings and client setup.

const { MongoClient } = require('mongodb');

const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017';
const databaseName = 'appdb';
const collectionName = 'orders';

async function createAndVerifyCollection(database, name) {
  await database.createCollection(name);
  const matches = await database.listCollections(
    { name },
    { nameOnly: true }
  ).toArray();
  return matches.length === 1;
}

async function main() {
  const client = new MongoClient(uri, { serverSelectionTimeoutMS: 3000 });
  try {
    await client.connect();
    const database = client.db(databaseName);
    const present = await createAndVerifyCollection(database, collectionName);
    console.log(`Collection present: ${present}`);
  } catch (error) {
    console.error(`${error.name}: ${error.message}`);
    process.exitCode = 1;
  } finally {
    await client.close();
  }
}

if (require.main === module) {
  main();
}

module.exports = { createAndVerifyCollection };

createCollection() resolves to a collection handle after the server creates it. The finally block closes the client even if the operation rejects. A long-running service usually keeps one MongoClient open and reuses its connection pool instead.

Step 3: Run the script and verify the collection

Run the named file with Node.js. The script prints the collection name only after its create request succeeds.

node create_collection.js

In this environment, I ran the program and received this connection failure because no MongoDB server was listening at the local address:

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
Node.js script reports a MongoDB connection refusal at 127.0.0.1:27017

After connecting to your own server, the script prints Collection present: true when its filtered query finds one result. The query checks the database selected by that handle rather than a similarly named collection elsewhere.

listCollections() returns a cursor over collection metadata. The name filter avoids loading unrelated entries, and nameOnly asks for names rather than full collection details. Calling toArray() collects the filtered results so the program can check their count.

Collection Creation Edge Cases

The server must be reachable before collection operations can run. Use the condition in the table to choose the next check.

SituationWhat happensNext action
The server refuses the connectionServer selection fails before collection creationCheck the URI, server availability and network access
You need an empty collection or validatorExplicit createCollection() sends collection optionsPass the options object as the second argument
You insert into a collection that is absentMongoDB creates the collection with the first documentUse insertOne() if no empty collection is needed
You run creation againA conflicting existing collection can produce NamespaceExistsCheck listCollections() or handle the expected existing state

MongoDB’s default validator action rejects documents that fail the rules. A warning action can log violations while still allowing writes, which helps when observing a new rule before enforcing it.

A capped collection needs a maximum size in bytes. MongoDB removes older documents as the collection reaches that limit. Consult the createCollection reference for supported options and requirements.

Creation can be repeated safely when the collection already has the same name and options. A conflicting collection with different options can return NamespaceExists, so inspect its configuration instead of dropping it to make the call pass.

A refusal happens before the create request, so confirm the deployment address and network access.

Conclusion

Select the intended database, verify the collection there, and manage MongoClient lifetime deliberately.

Next, see CodeForGeek’s database guide and insertMany tutorial. MongoDB’s official driver guide covers collection listing.

FAQ

These answers cover the common choices that come up when creating a collection from a Node.js app.

How do I create an empty MongoDB collection in Node.js?

Connect with MongoClient, select a database with client.db(), then await database.createCollection(‘name’). It creates the collection without inserting a document.

Does MongoDB create a collection when I insert a document?

Yes. MongoDB creates a missing collection when the first document is inserted, so explicit creation is only needed when the collection must exist before that write or needs options.

How can I check whether a collection exists?

Call database.listCollections({ name: ‘orders’ }, { nameOnly: true }).toArray() and check whether the returned array contains a result.

Aditya Gupta
Aditya Gupta

Aditya Gupta is a founding member and editor at CodeForGeek. He first found his way into tech by reading articles, and now writes approachable guides to Node.js security, authentication, AI tools, coding agents, and web scraping.

Articles: 529