In this tutorial, we will be learning about the Model-View-Controller (MVC) architecture in Node.js and how to use MongoDB with Express to build a complete Node.js application. We will go through the entire process step by step, from setting up the project to creating models, views, and controllers, to performing CRUD operations with MongoDB.
What is MVC Architecture?
MVC is a design pattern that divides an application into three main components: Models, Views, and Controllers.
- Models: Models represent the data of the application. They interact with the database to perform CRUD operations.
- Views: Views are the user interface of the application. They are responsible for rendering data to the user.
- Controllers: Controllers act as middlemen between the models and views. They handle user inputs, process data, and send responses back to the user.
Setting Up the Project
To get started, make sure you have Node.js and MongoDB installed on your system. You can install Node.js from the official website (https://nodejs.org) and MongoDB from the MongoDB website (https://www.mongodb.com/).
- Create a new directory for your project and navigate into it.
- Run
npm init -y
to create a newpackage.json
file. - Install Express, Mongoose (MongoDB driver for Node.js), and other necessary packages by running:
npm install express mongoose body-parser
- Create an
app.js
file in your project directory.
Creating Models
In this example, we will create a simple model for a User
object.
- Create a new folder called
models
within your project directory. - Create a new file called
userModel.js
inside themodels
folder.
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Creating Controllers
Next, we will create a controller for handling user requests.
- Create a new folder called
controllers
within your project directory. - Create a new file called
userController.js
inside thecontrollers
folder.
const User = require('../models/userModel');
const getUser = async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
}
const createUser = async (req, res) => {
const user = req.body;
try {
const newUser = await User.create(user);
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
}
module.exports = {
getUser,
createUser
};
Creating Routes
Now, we will create routes to map incoming requests to the appropriate controller actions.
- Create a new folder called
routes
within your project directory. - Create a new file called
userRoutes.js
inside theroutes
folder.
const express = require('express');
const router = express.Router();
const { getUser, createUser } = require('../controllers/userController');
router.get('/users', getUser);
router.post('/users', createUser);
module.exports = router;
Setting Up Express
In the app.js
file, set up Express and connect to MongoDB.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
const app = express();
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/node-mvc', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Connected to MongoDB');
});
app.use('/api', userRoutes);
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Testing the Application
- Start MongoDB by running
mongod
in a separate terminal window. - Start the Node.js application by running
node app.js
. - Use Postman or any other API testing tool to test the
/api/users
endpoint.
That’s it! You have now created a complete Node.js application using the MVC architecture with MongoDB and Express. Feel free to expand on this example by adding more models, views, and controllers to build more complex applications.
{23-9-2024}
Good topic
❤❤❤
why you could delete app.listen without any problem ???
{2023-10-05}
Good tutorial on NodeJS and MongoDB you have here. God bless your contribution. Is there Github clone for this NodeJS MongoDB video classes? It will better help student t learn faster rather than typing one after the other while the video plays on.
🙏🙏🙏
hello sir can you please tell me in which video's description you have inserted the code for curd operations I have written code for post req data is inserted in json file but it is not showing any response in postman
const createMovie=(req,res)=>{
const newId=movies[movies.length – 1].id + 1;
const newMovie=Object.assign({id:newId},req.body);
movies.push(newMovie);
//201 we added new movie
fs.writeFileSync('./data/movies.json',JSON.stringify(movies),(err)=>{
console.log(err);
res.status(201).json({
status:"sucescc",
data:{
movies:newMovie
}
})
})
}
app.post('/api/v1/movies',createMovie);
🙏👍👍