- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
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.
Key Features of Collection Creation
- 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.
- On-Demand Creation: If you perform an insert operation on a collection that doesn't exist yet, MongoDB will lazily create it for you.
- Explicit Creation: By using the
createCollectionmethod, you can pre-define specific configurations, such as memory limits (capped collections) or validation rules.
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
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;
}
}
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.
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(ormongofor older versions). - Switch to your database:
use ecommerce_db
- List all collections in the current database:
show collections
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
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.