Node.js MongoDB Create Collection

In the world of MongoDB, a collection is a grouping of documents. If you are coming from a SQL background, you can think of a collection as the equivalent of a table. However, unlike tables, collections do not enforce a strict schema by default, allowing you to store documents with different structures side-by-side. While MongoDB can create collections automatically when you first insert data, there are many scenarios where you'll want to create them explicitly using Node.js.

Developer Tip: Even though MongoDB is "schemaless," it is a best practice to keep documents within the same collection logically related (e.g., keeping "Users" and "Orders" in separate collections).

 

Key Features of Collection Creation

  1. Flexible Schema: Documents in the same collection don't need to have the same set of fields or data types, though they usually share a similar purpose.
  2. On-Demand Creation: If you perform an insert operation on a collection that doesn't exist yet, MongoDB will lazily create it for you.
  3. Explicit Creation: By using the createCollection method, you can pre-define specific configurations, such as memory limits (capped collections) or validation rules.
Best Practice: Use explicit creation when you need to set up Capped Collections (fixed-size collections that overwrite old data) or when adding JSON Schema Validation to ensure data integrity.

 

Step 1 Prerequisites

Before writing your script, ensure you have a Node.js environment ready and the official MongoDB driver installed in your project folder. You should also have a MongoDB instance running locally or a connection string for a MongoDB Atlas cluster.

npm install mongodb
Watch Out: Ensure your MongoDB server is actually running before executing your Node.js script, or the connection will timeout with an error.

Step 2 Connect to MongoDB

To interact with the database, we use the MongoClient class. It is important to handle connections asynchronously to prevent blocking your application's execution.

Example Code

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

// Connection URL (Default for local MongoDB)
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'ecommerce_db'; // Name of the database you want to use

async function connectToDatabase() {
  const client = new MongoClient(url);

  try {
    // Attempt to connect to the server
    await client.connect();
    console.log('Successfully connected to MongoDB server');

    const db = client.db(dbName);
    return { db, client };
  } catch (error) {
    console.error('Connection failed:', error.message);
    throw error;
  }
}
Common Mistake: Hardcoding your connection string (especially with passwords) directly in the code. Always use environment variables (like process.env.MONGODB_URI) for sensitive information.

Step 3 Create a Collection

To explicitly create a collection, we use the db.createCollection() method. This is useful for initializing your database structure during an application setup or deployment script.

Example Code

async function runSetup() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);

    // Create a collection named 'products'
    const collectionName = 'products';
    await db.createCollection(collectionName);
    
    console.log(`Success: Collection '${collectionName}' is ready.`);
  } catch (err) {
    // Handle cases where the collection might already exist
    console.error('Error creating collection:', err.message);
  } finally {
    await client.close();
  }
}

runSetup();

Output:

Success: Collection 'products' is ready.
Watch Out: If you try to create a collection that already exists, MongoDB will throw an error. In a real-world production script, you should wrap this in a try-catch block to handle existing collections gracefully.

Step 4 Verify the Collection

After running your script, it is a good habit to verify that the collection was actually created. You can do this via the command line or a GUI.

  • Open your terminal and type mongosh (or mongo for older versions).
  • Switch to your database:
use ecommerce_db
  • List all collections in the current database:
show collections
Developer Tip: If you prefer a visual interface, download MongoDB Compass. It allows you to see your collections, documents, and even analyze your schema visually.

Step 5 Insert Data into the Collection

While createCollection prepares the container, the collection only becomes useful once it holds data. You can obtain a reference to your collection using db.collection() and then perform operations like insertOne.

Example Code

async function addInitialProduct() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('products');

    // Real-world example: Adding a product document
    const product = { 
      sku: 'LAP-123', 
      name: 'Pro Laptop', 
      price: 1200, 
      inStock: true 
    };

    const result = await collection.insertOne(product);
    console.log(`Document inserted with ID: ${result.insertedId}`);
  } finally {
    await client.close();
  }
}

addInitialProduct().catch(console.error);

Output:

Document inserted with ID: 61b0fa1e4a6c1e8b76a7c2d3
Common Mistake: Forgetting to await the client.close() call. If your script ends before the connection closes, you might leave hanging connections to your database.

 

Summary

Managing collections in MongoDB with Node.js is straightforward but offers significant control. You can let MongoDB handle collection creation automatically by simply inserting data, or you can use createCollection for more advanced, explicit setups. By mastering these basics, you've taken the first step toward building scalable, document-oriented applications. Remember to always handle your database connections cleanly and use environment variables to keep your credentials secure.