Express.js Working with MongoDB

MongoDB is a NoSQL database that integrates smoothly with Express.js, making it popular for modern web applications. Together, they let you build dynamic, scalable, and efficient backends. This tutorial shows you how to connect MongoDB with Express.js and demonstrates CRUD operations.



Express.js and MongoDB Integration

Express.js is a Node.js framework that streamlines handling HTTP requests. MongoDB stores data as flexible documents, letting you adjust data structures with minimal overhead. With Express.js and MongoDB, you can define routes easily, model data clearly, and persist information powerfully.

Understanding Mongoose

Mongoose is a Node.js library that provides a schema-based solution for MongoDB. You define schemas, then build models that map directly to collections. This approach helps you validate fields and manage queries efficiently.

How to Connect to MongoDB Using Mongoose

  1. Install Dependencies
    npm install express mongoose
    
  2. Set Up Connection
    // app.js
    const express = require('express'); // Importing Express.js
    const mongoose = require('mongoose'); // Importing Mongoose
    
    const app = express(); 
    app.use(express.json()); // Parse incoming JSON requests
    
    // Connect to MongoDB (replace <username>, <password>, and <dbname> with actual values)
    mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }).then(() => {
      console.log('Connected to MongoDB');
    }).catch((err) => {
      console.error('MongoDB connection error:', err);
    });
    
    // Start the server
    app.listen(3000, () => {
      console.log('Server running on port 3000');
    });
    

    Replace <username>, <password>, and <dbname> with valid credentials or use a local connection string (mongodb://127.0.0.1:27017/mydatabase)

Defining a Mongoose Model

You use Mongoose schemas and models to define the shape of your data. For example, you might store users with a name and email.

// userModel.js
const mongoose = require('mongoose'); // Importing Mongoose

// Define a schema for the user
const userSchema = new mongoose.Schema({
  name: String, // User's name
  email: String // User's email
});

// Create a model from the schema
const User = mongoose.model('User', userSchema);

module.exports = User;

You do not need to create the collection manually; MongoDB handles that when you insert data.

Implementing CRUD Operations

You perform Create, Read, Update, and Delete operations through Express.js routes. Each route corresponds to a URL endpoint.

// userRoutes.js
const express = require('express'); // Importing Express.js
const router = express.Router();
const User = require('./userModel'); // Importing the User model

// Create a new user
router.post('/users', async (req, res) => {
  try {
    // Example Data: { "name": "Rahul", "email": "[email protected]" }
    const newUser = new User(req.body);
    const savedUser = await newUser.save(); // Save the user to MongoDB
    res.status(201).json(savedUser);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// Read all users
router.get('/users', async (req, res) => {
  try {
    const users = await User.find(); // Retrieve all user documents
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Update a user by ID
router.put('/users/:id', async (req, res) => {
  try {
    // Example Data: { "name": "Emma", "email": "[email protected]" }
    const updatedUser = await User.findByIdAndUpdate(
      req.params.id, // The ID of the user to update
      req.body, // The updated data
      { new: true } // Return the updated document
    );
    res.json(updatedUser);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// Delete a user by ID
router.delete('/users/:id', async (req, res) => {
  try {
    const deletedUser = await User.findByIdAndRemove(req.params.id); // Remove the user
    if (!deletedUser) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json({ message: 'User deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;

Add the following code to app.js:

// app.js (add this after the Mongoose connection)
const userRoutes = require('./userRoutes'); // Importing the user routes
app.use('/api', userRoutes); // Prefix routes with /api

Send the request using an API testing tool like Postman or through a web browser.

Testing Your Setup

  • Run the Server
    node app.js
    
  • Create a User (POST) Send a POST request to http://localhost:3000/api/users with JSON data, for example:
    { "name": "John", "email": "[email protected]" }
    
  • Retrieve All Users (GET) Make a GET request to http://localhost:3000/api/users.
  • Update a User (PUT) Send a PUT request to http://localhost:3000/api/users/<user_id> with updated data in JSON.
  • Delete a User (DELETE) Send a DELETE request to http://localhost:3000/api/users/<user_id>.

Conclusion

You have learned how to integrate Express.js with MongoDB using Mongoose. You now know how to establish a database connection, define data models, and implement CRUD operations. With this foundation in place, you can build scalable applications that handle data efficiently.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram

Keep W3schools Growing with Your Support!
❤️ Support W3schools