๐ Overview
This guide shows you how to connect a MongoDB database to an Express.js application using the official mongodb driver. This is useful for developers building full-stack JavaScript applications that need to store and retrieve data.
๐ง Prerequisites
Before you begin, make sure you have:
- Node.js and npm installed
- MongoDB installed locally or a MongoDB Atlas cloud database
- Basic knowledge of JavaScript and Express.js
๐ ๏ธ Step 1: Create a New Express App
A. Create a new project folder:
mkdir express-mongo-app
cd express-mongo-app
B. Initialize a Node.js project:
npm init -y
npm install express mongodb
C. Create an index.js file with this boilerplate:
// CommonJS (used in Node.js by default, not ES6 module)
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
๐ Step 2: Connect to MongoDB
A. At the top of index.js, import the MongoDB client:
const { MongoClient } = require('mongodb');
B. Define your connection URL and database name:
const uri = 'mongodb://localhost:27017'; // Replace with your MongoDB Atlas URI if using cloud
const client = new MongoClient(uri);
const dbName = 'myDatabase';
C. Create an async function to connect:
async function run() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const db = client.db(dbName);
const collection = db.collection('users');
// Sample route to insert a user
app.post('/users', async (req, res) => {
const user = req.body;
const result = await collection.insertOne(user);
res.send(result);
});
// Sample route to get all users
app.get('/users', async (req, res) => {
const users = await collection.find({}).toArray();
res.send(users);
});
} catch (err) {
console.error(err);
}
}
run();
โถ๏ธ Step 3: Test the App
A. Start the server:
node index.js
B. Use Postman or curl to test endpoints:
- Insert a user:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "Mohamed", "email": "[email protected]"}'
- Get all users:
curl http://localhost:3000/users
๐งผ Step 4: Clean Up and Best Practices
- Store your MongoDB URI in an environment variable (e.g., .env)
- Handle connection errors and cleanup with process.on('SIGINT')
- Use async/await consistently for clarity
โ Summary
Youโve learned how to:
- Set up a Node.js + Express.js app
- Connect to MongoDB (local or Atlas)
- Insert and retrieve data with API endpoints
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.