Welcome to The Coding College! In this tutorial, we’ll guide you through the process of creating a collection in MongoDB using Node.js. Collections in MongoDB are equivalent to tables in relational databases and are used to store documents.
Prerequisites
Before starting, ensure the following:
- MongoDB Installed: Install MongoDB.
- Node.js Installed: Install Node.js.
- MongoDB Driver Installed: Install it using the following command:
npm install mongodb
Step 1: Set Up a MongoDB Connection
Create a file createCollection.js
and set up the connection to MongoDB:
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017'; // Default MongoDB URL
const client = new MongoClient(url);
// Database Name
const dbName = 'myNewDatabase'; // Replace with your database name
async function createCollection() {
try {
// Connect to the MongoDB server
await client.connect();
console.log('Connected to MongoDB server.');
// Select the database
const db = client.db(dbName);
// Create a collection
const collectionName = 'users';
await db.createCollection(collectionName);
console.log(`Collection '${collectionName}' created.`);
} catch (err) {
console.error('Error:', err.message);
} finally {
// Close the connection
await client.close();
console.log('Connection closed.');
}
}
createCollection();
Step 2: Run the Script
Run the createCollection.js
script using Node.js:
node createCollection.js
Output
You should see the following output if the collection is successfully created:
Connected to MongoDB server.
Collection 'users' created.
Connection closed.
Step 3: Verify Collection Creation
- Open the MongoDB Shell or MongoDB Compass.
- Use the following command in the MongoDB shell to check the collections:
use myNewDatabase show collections
You should seeusers
listed as a collection.
Creating Collections with Options
You can add specific options while creating a collection. For example, creating a capped collection:
async function createCappedCollection() {
try {
await client.connect();
const db = client.db(dbName);
// Create a capped collection
await db.createCollection('logs', {
capped: true,
size: 1024, // Max size in bytes
max: 100, // Max number of documents
});
console.log("Capped collection 'logs' created.");
} catch (err) {
console.error('Error:', err.message);
} finally {
await client.close();
}
}
createCappedCollection();
Best Practices
- Collection Naming: Use meaningful names to organize your data effectively.
- Indexes: Add indexes to collections after creation for optimized queries.
- Capped Collections: Use them for logging or other cases where data must overwrite old records.
- Schema Validation: Even though MongoDB is schema-less, use validation rules for consistency.
Example Output for Capped Collection
Running the capped collection script gives:
Connected to MongoDB server.
Capped collection 'logs' created.
Connection closed.
Conclusion
Creating collections in MongoDB with Node.js is simple and flexible. Whether it’s a basic collection or a capped one, MongoDB provides extensive customization options. For more programming tutorials, visit The Coding College and enhance your coding skills!