,

Complete NODE JS Course with MongoDB and Express using MVC Architecture in NODE JS

Posted by


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/).

  1. Create a new directory for your project and navigate into it.
  2. Run npm init -y to create a new package.json file.
  3. Install Express, Mongoose (MongoDB driver for Node.js), and other necessary packages by running:
    npm install express mongoose body-parser
  4. Create an app.js file in your project directory.

Creating Models

In this example, we will create a simple model for a User object.

  1. Create a new folder called models within your project directory.
  2. Create a new file called userModel.js inside the models 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.

  1. Create a new folder called controllers within your project directory.
  2. Create a new file called userController.js inside the controllers 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.

  1. Create a new folder called routes within your project directory.
  2. Create a new file called userRoutes.js inside the routes 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

  1. Start MongoDB by running mongod in a separate terminal window.
  2. Start the Node.js application by running node app.js.
  3. 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.

0 0 votes
Article Rating

Leave a Reply

9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@mohamedibrahemsaad573
4 hours ago

{23-9-2024}

@SharQawyCS
4 hours ago

Good topic

@hassannouri9796
4 hours ago

❤❤❤

@AberrahimCoder
4 hours ago

why you could delete app.listen without any problem ???

@Pareshbpatel
4 hours ago

{2023-10-05}

@olamijiakeemodeyemi9320
4 hours ago

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.

@littlewonder8641
4 hours ago

🙏🙏🙏

@kishansingh-yw5ul
4 hours ago

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);

@rishiraj2548
4 hours ago

🙏👍👍

9
0
Would love your thoughts, please comment.x
()
x