Express with MongoDB

📘 Express.js 👁 46 views 📅 Nov 05, 2025
⏱ Estimated reading time: 3 min

MongoDB is a NoSQL database that stores data in JSON-like documents. When combined with Express.js, it is ideal for building REST APIs, CRUD applications, and full-stack apps.


1. Prerequisites

  • Install Node.js and npm

  • Install MongoDB locally or use a cloud service like MongoDB Atlas

  • Have a database ready (e.g., express_db)


2. Install Required Packages

npm install express mongoose
  • mongoose – ODM (Object Data Modeling) library for MongoDB

  • Provides schemas, models, validation, and queries


3. Connect Express to MongoDB

const express = require('express'); const mongoose = require('mongoose'); const app = express(); app.use(express.json()); const PORT = process.env.PORT || 3000; const MONGO_URI = 'mongodb://localhost:27017/express_db'; // local MongoDB // Connect to MongoDB mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('MongoDB connection error:', err));
  • useNewUrlParser and useUnifiedTopology are recommended options

  • For MongoDB Atlas, use the connection string provided by Atlas


4. Create a Mongoose Schema and Model

User Schema Example:

const { Schema, model } = mongoose; const userSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: Number, }, { timestamps: true }); const User = model('User', userSchema);
  • timestamps: true automatically adds createdAt and updatedAt fields

  • Validation can be added in the schema (e.g., required, unique)


5. CRUD Operations

Create a User (POST):

app.post('/users', async (req, res) => { try { const user = new User(req.body); const savedUser = await user.save(); res.status(201).json(savedUser); } catch (err) { res.status(400).json({ error: err.message }); } });

Read Users (GET):

// Get all users app.get('/users', async (req, res) => { const users = await User.find(); res.json(users); }); // Get user by ID app.get('/users/:id', async (req, res) => { try { const user = await User.findById(req.params.id); if (!user) return res.status(404).json({ error: 'User not found' }); res.json(user); } catch (err) { res.status(400).json({ error: 'Invalid ID' }); } });

Update a User (PUT/PATCH):

app.put('/users/:id', async (req, res) => { try { const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); if (!updatedUser) return res.status(404).json({ error: 'User not found' }); res.json(updatedUser); } catch (err) { res.status(400).json({ error: 'Invalid ID' }); } });

Delete a User (DELETE):

app.delete('/users/:id', async (req, res) => { try { const deletedUser = await User.findByIdAndDelete(req.params.id); if (!deletedUser) return res.status(404).json({ error: 'User not found' }); res.json({ message: 'User deleted' }); } catch (err) { res.status(400).json({ error: 'Invalid ID' }); } });

6. Best Practices

  1. Use Mongoose validation for data integrity

  2. Use async/await for cleaner asynchronous code

  3. Store MongoDB connection string in environment variables (.env)

  4. Handle errors with centralized middleware

  5. Consider indexes for fields used in queries (like email)

  6. Use express-validator for extra input validation


7. Example Project Structure

express-mongo/ │ ├─ models/ │ └─ User.js // Mongoose model ├─ routes/ │ └─ users.js // User CRUD routes ├─ app.js // Express setup & MongoDB connection └─ package.json
  • Keeps code modular and organized

  • Easy to scale for larger applications


Using Express with MongoDB and Mongoose allows you to quickly build REST APIs and full-stack applications with flexible schema design and powerful querying.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes