Welcome to The Coding College! In this tutorial, we’ll explore how to integrate MongoDB with Node.js to build robust, scalable applications. MongoDB is a NoSQL database that stores data in JSON-like documents, making it highly flexible and ideal for modern applications.
Why Use MongoDB with Node.js?
- Scalability: MongoDB is horizontally scalable, making it suitable for large datasets.
- JSON-Like Documents: Seamless integration with JavaScript, as both use JSON-like structures.
- Flexibility: Schema-less design allows rapid iteration during development.
- Rich Query Language: Supports powerful queries, aggregations, and indexing.
Prerequisites
To follow along, ensure you have:
- Node.js Installed: Download Node.js.
- MongoDB Installed: Download MongoDB or use a cloud service like MongoDB Atlas.
- MongoDB Client: Install a GUI like MongoDB Compass for easier database management.
Step 1: Install the MongoDB Driver
In your Node.js project, install the official MongoDB driver:
npm install mongodb
Step 2: Connect to MongoDB
Create a new file mongodbConnect.js
and set up the connection:
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017'; // Replace with your MongoDB URI
const client = new MongoClient(url);
// Database Name
const dbName = 'myDatabase';
async function connectToDatabase() {
try {
await client.connect();
console.log('Connected successfully to MongoDB!');
const db = client.db(dbName);
// Perform operations here
console.log('Database:', db.databaseName);
} catch (err) {
console.error('Connection failed:', err.message);
} finally {
await client.close();
}
}
connectToDatabase();
Step 3: Create a Collection
Collections in MongoDB are analogous to tables in relational databases.
async function createCollection() {
const db = client.db(dbName);
const collection = db.collection('users'); // Creates a 'users' collection if it doesn’t exist
console.log('Collection created:', collection.collectionName);
}
Step 4: Insert Documents
To add data into a collection:
async function insertDocuments() {
const db = client.db(dbName);
const collection = db.collection('users');
const result = await collection.insertMany([
{ name: 'Alice', age: 25, email: '[email protected]' },
{ name: 'Bob', age: 30, email: '[email protected]' },
]);
console.log(`${result.insertedCount} documents inserted.`);
}
Step 5: Query Documents
Retrieve data from the collection:
async function findDocuments() {
const db = client.db(dbName);
const collection = db.collection('users');
const users = await collection.find({ age: { $gt: 25 } }).toArray(); // Finds users older than 25
console.log('Found documents:', users);
}
Step 6: Update Documents
Modify existing records:
async function updateDocument() {
const db = client.db(dbName);
const collection = db.collection('users');
const result = await collection.updateOne(
{ name: 'Alice' },
{ $set: { age: 26 } }
);
console.log(`${result.modifiedCount} document(s) updated.`);
}
Step 7: Delete Documents
Remove documents from the collection:
async function deleteDocument() {
const db = client.db(dbName);
const collection = db.collection('users');
const result = await collection.deleteOne({ name: 'Bob' });
console.log(`${result.deletedCount} document(s) deleted.`);
}
Full CRUD Operations Example
Here’s how to combine all CRUD operations into one script:
async function main() {
try {
await client.connect();
console.log('Connected to MongoDB!');
const db = client.db(dbName);
const collection = db.collection('users');
// Insert
await collection.insertOne({ name: 'John', age: 35 });
console.log('Document inserted.');
// Read
const user = await collection.findOne({ name: 'John' });
console.log('Found User:', user);
// Update
await collection.updateOne({ name: 'John' }, { $set: { age: 36 } });
console.log('Document updated.');
// Delete
await collection.deleteOne({ name: 'John' });
console.log('Document deleted.');
} catch (err) {
console.error(err.message);
} finally {
await client.close();
}
}
main();
Best Practices
- Use Environment Variables: Store sensitive data like database credentials securely using
.env
files. - Indexes: Create indexes to optimize query performance.
- Validation: Define schemas to validate data before inserting it into MongoDB.
- Connection Pooling: Reuse connections for better performance in production.
Example Output
If you run the script, you’ll see:
Connected successfully to MongoDB!
Document inserted.
Found User: { _id: 1, name: 'John', age: 35 }
Document updated.
Document deleted.
Conclusion
Integrating MongoDB with Node.js provides a flexible and powerful way to manage data for your applications. With its JSON-like document structure and Node.js’s asynchronous capabilities, you can build fast and scalable systems.
For more tutorials on programming and databases, visit The Coding College. We’re here to simplify your learning journey!