Using Express.js with Mongoose is a common setup for building applications with MongoDB. Here's a step-by-step guide to help you get started:
Step 1: Set Up a New Express.js Project
- Initialize a New Project:
mkdir express-mongoose-app
cd express-mongoose-app
npm init -y
- Install Required Packages:
npm install express mongoose
npm install dotenv
Step 2: Configure Environment Variables
-
Create a
.env
File: Create a.env
file in the root of your project to store environment variables:
PORT=3000
MONGODB_URI=mongodb://localhost:27017/mydatabase
-
Load Environment Variables:
Create a
config.js
file to load environment variables:
require('dotenv').config();
module.exports = {
port: process.env.PORT || 3000,
mongodbUri: process.env.MONGODB_URI,
};
Step 3: Set Up Mongoose
- Create a Directory Structure:
mkdir -p src/models src/controllers src/routes src/config
-
Create Mongoose Connection:
Create
src/config/mongoose.js
to handle the connection to MongoDB:
const mongoose = require('mongoose');
const config = require('../../config');
const connectDB = async () => {
try {
await mongoose.connect(config.mongodbUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
console.log('MongoDB connected');
} catch (error) {
console.error('MongoDB connection failed:', error.message);
process.exit(1);
}
};
module.exports = connectDB;
Step 4: Create Mongoose Models
-
Create a User Model:
Create
src/models/User.js
:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Step 5: Create Controllers
-
Create User Controller:
Create
src/controllers/userController.js
:
const User = require('../models/User');
exports.getUsers = async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
exports.getUser = async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
exports.createUser = async (req, res) => {
const { name, email, password } = req.body;
const userExists = await User.findOne({ email });
if (userExists) {
return res.status(400).json({ message: 'User already exists' });
}
const user = new User({
name,
email,
password,
});
try {
const newUser = await user.save();
res.status(201).json(newUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
};
exports.updateUser = async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
user.password = req.body.password || user.password;
const updatedUser = await user.save();
res.json(updatedUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
};
exports.deleteUser = async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
await user.remove();
res.json({ message: 'User deleted' });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
Step 6: Create Routes
-
Create User Routes:
Create
src/routes/userRoutes.js
:
const express = require('express');
const { getUsers, getUser, createUser, updateUser, deleteUser } = require('../controllers/userController');
const router = express.Router();
router.get('/users', getUsers);
router.get('/users/:id', getUser);
router.post('/users', createUser);
router.put('/users/:id', updateUser);
router.delete('/users/:id', deleteUser);
module.exports = router;
Step 7: Set Up the Express Server
-
Create the Server:
Create
src/index.js
:
const express = require('express');
const connectDB = require('./config/mongoose');
const userRoutes = require('./routes/userRoutes');
const config = require('../config');
const app = express();
// Connect to MongoDB
connectDB();
// Middleware to parse JSON
app.use(express.json());
// Routes
app.use('/api', userRoutes);
const PORT = config.port;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Step 8: Run the Application
- Start the Express Application:
node src/index.js
Step 9: Test the API
-
Test Endpoints:
Use a tool like Postman or curl to test the RESTful API endpoints:-
GET /api/users
: Retrieve all users. -
GET /api/users/:id
: Retrieve a user by ID. -
POST /api/users
: Create a new user.
{ "name": "John Doe", "email": "john@example.com", "password": "password" }
-
-
PUT /api/users/:id
: Update a user by ID. -
DELETE /api/users/:id
: Delete a user by ID.
This guide provides a foundational approach to integrating Mongoose with an Express.js application. You can further expand and customize it based on your application's requirements.
Support My Work โค๏ธ
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me ๐
Letโs stay connected! You can follow me or reach out on these platforms:
๐น YouTube โ Tutorials, insights & tech content
๐น LinkedIn โ Professional updates & networking
๐น GitHub โ My open-source projects & contributions
๐น Instagram โ Behind-the-scenes & personal updates
๐น X (formerly Twitter) โ Quick thoughts & tech discussions
Iโd love to hear from youโwhether itโs feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)