Here is an example of how to structure a Node.
js application using the Model-View-Controller (MVC)
pattern, with a focus on routing, controllers, and models:
1. Project Structure:
Code
your-project/
├── models/
│ └── user.js
├── controllers/
│ └── userController.js
├── routes/
│ └── userRoutes.js
├── app.js
└── package.json
2. Model (models/user.js):
Represents the data structure and logic for interacting with the database and Example.
JavaScript
// models/user.js
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
static getAll() {
// Simulate fetching all users from a database
return [
];
static getById(id) {
// Simulate fetching a user by ID from a database
return User.getAll().find((user) => user.id === id);
module.exports = User;
3. Controller (controllers/userController.js):
Handles incoming requests and interacts with the model to retrieve or manipulate data.
Example:
JavaScript
// controllers/userController.js
const User = require("../models/user");
exports.getAllUsers = (req, res) => {
const users = User.getAll();
res.json(users);
};
exports.getUserById = (req, res) => {
const userId = parseInt(req.params.id);
const user = User.getById(userId);
if (user) {
res.json(user);
} else {
res.status(404).json({ message: "User not found" });
};
4. Router (routes/userRoutes.js):
Defines the routes and maps them to the corresponding controller actions and Example.
JavaScript
// routes/userRoutes.js
const express = require("express");
const router = express.Router();
const userController = require("../controllers/userController");
router.get("/", userController.getAllUsers);
router.get("/:id", userController.getUserById);
module.exports = router;
5. Main Application (app.js): Sets up the Express app and uses the router and Example.
JavaScript
// app.js
const express = require("express");
const app = express();
const userRoutes = require("./routes/userRoutes");
app.use("/users", userRoutes);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
Model:
The User class represents the user data and provides methods to fetch user data.
Controller:
The userController handles requests related to users. It uses the User model to fetch data and sends
responses.
Router:
The userRoutes defines the routes for user-related requests, mapping them to the corresponding
controller actions.
App:
The app.js sets up the Express application, uses the userRoutes to handle requests to the /users
endpoint, and starts the server.
This structure separates concerns, making the code easier to maintain, test, and scale.