Developing a MERN (MongoDB, Express.js, React, and Node.js) Project (Part 2)

In Part 1, we have setup the frontend and backend of our web app with basic configuration. What we’ll do next is defining MongoDB schemas and implementing the route handlers in our Express.js backend, and wiring the routes to our Express application. Let’s get going.

Defining MongoDB Schemas

MongoDB schemas define the structure of our data models. In Mongoose, each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

Inside our backend folder, we create a folder named “models” to store our MongoDB schema files.

Next, we create separate files for each schema, where each file will define the schema for a specific data model. For example, we might have a MenuItem schema for restaurant menu items and a User schema for user accounts. Let’s create a simple example for a MenuItem schema.

We create a file named “menuItem.js” in “models” folder and paste this content in it:

import mongoose, { mongo } from "mongoose";

const menuItemSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    images: {
        type: Array,
        required: true,
        default: [],
    },
    category: {
        type: String,
        required: true,
    },
    description: {
        type: String,
        required: true,
    },
    reviews: {
        type: String,
        required: true,
        default: [],
    },
    rating: {
        type: Number,
        required: true,
        default: 0,
    },
    numberOfReviews: {
        type: Number,
        required: true,
    },
    price: {
        type: Number,
        required: true,
    },
},
{ timestamps: true }
);

const menuItem = mongoose.model("MenuItem", menuItemSchema);

export default menuItem;

In this file, we define a MenuItem schema with fields like name, description, price, and category. Each field has a specified data type and may have additional constraints such as required.

Implementing Route Handlers

Route handlers in Express.js handle incoming HTTP requests and define how your server responds to those requests. You can define route handlers to perform CRUD operations, user authentication, and other application logic. Here’s how we implement route handlers for our application:

Inside our “backend” folder, we create a folder named “routes” to store our route handler files.

Then we create separate files for different sets of routes (e.g., menu routes, user routes), and we use Express Router to define routes and handle requests.

Now let’s create our first route handler by creating a “menuItemRoutes.js” file in “routes” folder. Here is the content of the file:

import express from "express";
import menuItem from "../models/menuItem.js";

const menuItemRoutes = express.Router();

const getMenuItems = async (req, res) => {
    const menuItems = await menuItem.find({});

    res.json({
        menuItems,
        pagination: {},
    });
};

menuItemRoutes.route("/").get(getMenuItems);

export default menuItemRoutes;

Finally we wire the routes to our Express application by importing and using them in “index.js” file. Here is the updated “index.js” file:

import dotenv from "dotenv";
dotenv.config();
import connectToDatabase from "./db.js";
import express from "express";
import cors from "cors";

// Routes
import menuItemRoutes from "./routes/menuItemRoutes.js";

connectToDatabase();
const app = express();
app.use(express.json());
app.use(cors());

app.use("/api/menuitems", menuItemRoutes);

const port = 5000;

app.get("/", (req, res) => {
    res.send("Api is running...");
})

app.listen(port, () => {
    console.log(`Server runs on port ${port}`);
});

In this setup, we import the “menuItemRoutes” from the “routes” directory and returned them as JSON. We can test whether everything is running smoothly buy running the backend server with our command:

npm run server

And navigating to “http://localhost:5000/api/menuitems” from our browser. We should see the following JSON response in the browser.

{"menuItems":[],"pagination":{}}

What we do is here basically, we make an API call from the backend via our browser and we get a response.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir