top of page
Writer's pictureCODING Z2M

How Express.js & Node.js Use Mongoose to Interact with MongoDB

Updated: 5 days ago


What is Mongoose?

Mongoose is an Object-Document Mapping (ODM) library that provides an Object Data Modeling (ODM) layer for Node.js & MongoDB. It provides a simple and efficient way to interact with MongoDB from Node.js applications. With Mongoose, you can define data models using a schema which provides a clear structure and built-in validation rules for your data that allows you to validate data before saving it to the database and then perform various operations on those models, such as creating, reading, updating, and deleting data in the MongoDB database. Mongoose is built on top of the official MongoDB Node.js driver and  it is widely used in Node.js applications that use MongoDB as the underlying database, as it simplifies the development process and makes it easier to work with MongoDB data.


In a MERN stack application (MongoDB, Express, React, Node.js), Mongoose is used on the backend (Node.js) to:

  1. Define the data structure (schema) for MongoDB collections.

  2. Perform CRUD (Create, Read, Update, Delete) operations easily.

  3. Validate data before it is saved to the database.

  4. Provide additional query helpers and middleware to streamline database operations.


Request Flow

  • HTTP Request (Client) → Express.js Route → Mongoose Model → MongoDB Database → Response (Client).

Frontend (React) sends a POST request to http://localhost:5000/api/users with user data.

Backend (Node.js + Express) receives the request, processes it, and uses Mongoose to save the data in MongoDB.



How Mongoose Is Used in a MERN Application

In a MERN stack application, Express.js and Node.js work together to handle HTTP requests and facilitate communication with the database through Mongoose. Let’s clarify how they connect:


Installation

First, you need to install Mongoose in your Node.js backend project:

npm install mongoose

 Node.js and Mongoose Connection

  • Node.js acts as the runtime environment for your backend.

  • Mongoose is imported into your Node.js application to handle the interaction with MongoDB.

  • The connection to MongoDB is established in your Node.js application using Mongoose’s connect method.

Example: Connecting Mongoose to MongoDB

const mongoose = require('mongoose');
const mongoURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(mongoURI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Failed to connect to MongoDB:', err));

This connection establishes the bridge between your Node.js application and the MongoDB database.


Defining a Schema

Define a schema to specify the structure of your data:

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 },
  createdAt: { type: Date, default: Date.now },
});
// Create a model based on the schema
const User = mongoose.model('User', userSchema);
module.exports = User;

Express.js and Routing

  • Express.js is a framework that simplifies handling HTTP requests.

  • It defines routes (e.g., /api/users) and maps them to controllers or middleware functions.

  • These controllers use Mongoose models to perform database operations like creating, reading, updating, and deleting documents.


How Express.js Uses Mongoose

  1. Express.js receives an HTTP request (e.g., POST request to /api/users).

  2. The corresponding route handler (or controller function) is triggered.

  3. Inside the route handler, Mongoose models are used to interact with MongoDB.

  4. The response is sent back to the client.

Example: Express.js Route Using Mongoose

const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
  .then(() => console.log('MongoDB connected'))
  .catch((err) => console.error('MongoDB connection error:', err));
// Define a Mongoose schema and model
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);
// Middleware to parse JSON
app.use(express.json());
// Define a POST route to create a new user
app.post('/api/users', async (req, res) => {
  try {
    const user = new User(req.body); // Create a new user with request body
    const savedUser = await user.save(); // Save to MongoDB using Mongoose
    res.status(201).json(savedUser); // Send the saved user as a response
  } catch (error) {
    res.status(400).json({ error: error.message }); // Handle errors
  }
});
// Start the Express server
app.listen(5000, () => console.log('Server running on port 5000'));


Key Points in the Example

  1. Mongoose in Node.js:

    • The mongoose.connect() function establishes the connection between Node.js and MongoDB.

    • Mongoose models (User in this example) are used to define and manipulate data in the database.

  2. Express.js Routes:

    • The /api/users route listens for POST requests.

    • Inside the route handler, User.save() (a Mongoose method) is called to store data in MongoDB.

  3. Middleware:

    • app.use(express.json()) parses the incoming JSON data, so it can be used in the request body (req.body).



How Express.js and Node.js Use Mongoose Together

  • Node.js handles the environment and runtime.

  • Express.js defines routes and handles HTTP requests.

  • Mongoose bridges the gap between the Express.js application and the MongoDB database:

    • It connects to the database.

    • It provides models and schema validation for the data.

    • It performs CRUD operations

2 views0 comments

Comments


bottom of page