MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It's highly scalable and can handle large volumes of data efficiently. In this tutorial, we'll explore how to integrate MongoDB with Node.js using the mongodb package. This guide will cover setting up your environment, connecting to a MongoDB database, performing CRUD operations, and implementing best practices.
Before you begin, ensure you have the following installed:
First, create a new directory for your project and initialize it using npm.
mkdir node-mongodb-example
cd node-mongodb-example
npm init -y
Next, install the mongodb package:
npm install mongodb
To connect to a MongoDB database, you'll need to use the MongoClient class from the mongodb package. Here's how you can set up a connection:
db.js.// db.js
const { MongoClient } = require('mongodb');
async function connectToDatabase() {
const uri = 'your_mongodb_connection_string'; // Replace with your MongoDB URI
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log('Connected to MongoDB');
return client.db('your_database_name'); // Replace with your database name
} catch (error) {
console.error('Error connecting to MongoDB', error);
throw error;
}
}
module.exports = connectToDatabase;
# .env file
MONGODB_URI=your_mongodb_connection_string
DATABASE_NAME=your_database_name
Update db.js to use the environment variables:
// db.js
require('dotenv').config();
const { MongoClient } = require('mongodb');
async function connectToDatabase() {
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log('Connected to MongoDB');
return client.db(process.env.DATABASE_NAME);
} catch (error) {
console.error('Error connecting to MongoDB', error);
throw error;
}
}
module.exports = connectToDatabase;
Now that you have a connection, let's perform some basic CRUD operations.
operations.js.// operations.js
const { ObjectId } = require('mongodb');
const connectToDatabase = require('./db');
async function createDocument(collectionName, document) {
const db = await connectToDatabase();
const collection = db.collection(collectionName);
try {
const result = await collection.insertOne(document);
console.log('Document inserted:', result.insertedId);
return result.insertedId;
} catch (error) {
console.error('Error inserting document', error);
throw error;
}
}
module.exports = { createDocument };
// index.js
const { createDocument } = require('./operations');
async function run() {
const document = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
await createDocument('users', document);
}
run().catch(console.error);
operations.js to include a read function.// operations.js
async function readDocuments(collectionName, query = {}) {
const db = await connectToDatabase();
const collection = db.collection(collectionName);
try {
const documents = await collection.find(query).toArray();
console.log('Documents found:', documents);
return documents;
} catch (error) {
console.error('Error reading documents', error);
throw error;
}
}
module.exports = { createDocument, readDocuments };
// index.js
const { createDocument, readDocuments } = require('./operations');
async function run() {
const document = { name: 'Jane Doe', age: 25, email: 'jane.doe@example.com' };
await createDocument('users', document);
const users = await readDocuments('users');
}
run().catch(console.error);
operations.js to include an update function.// operations.js
async function updateDocument(collectionName, filter, update) {
const db = await connectToDatabase();
const collection = db.collection(collectionName);
try {
const result = await collection.updateOne(filter, { $set: update });
console.log('Documents updated:', result.modifiedCount);
return result.modifiedCount;
} catch (error) {
console.error('Error updating document', error);
throw error;
}
}
module.exports = { createDocument, readDocuments, updateDocument };
// index.js
const { createDocument, readDocuments, updateDocument } = require('./operations');
async function run() {
const document = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
await createDocument('users', document);
const filter = { name: 'John Doe' };
const update = { age: 31 };
await updateDocument('users', filter, update);
}
run().catch(console.error);
operations.js to include a delete function.// operations.js
async function deleteDocument(collectionName, filter) {
const db = await connectToDatabase();
const collection = db.collection(collectionName);
try {
const result = await collection.deleteOne(filter);
console.log('Documents deleted:', result.deletedCount);
return result.deletedCount;
} catch (error) {
console.error('Error deleting document', error);
throw error;
}
}
module.exports = { createDocument, readDocuments, updateDocument, deleteDocument };
// index.js
const { createDocument, readDocuments, updateDocument, deleteDocument } = require('./operations');
async function run() {
const document = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
await createDocument('users', document);
const filter = { name: 'John Doe' };
await deleteDocument('users', filter);
}
run().catch(console.error);
Error Handling: Always handle errors gracefully. Use try-catch blocks and log errors appropriately.
Connection Management: Ensure that your MongoDB connection is properly managed. Consider using a connection pool or a connection management library like mongoose.
Environment Variables: Store sensitive information like database URIs in environment variables.
Asynchronous Operations: Use async/await to handle asynchronous operations, making your code cleaner and easier to read.
Validation: Validate user input before inserting it into the database to prevent errors and ensure data integrity.
In this tutorial, we've covered how to integrate MongoDB with Node.js using the mongodb package. We explored setting up a connection, performing CRUD operations, and implementing best practices. By following these steps, you should be able to build robust applications that interact with MongoDB effectively.