DEV Community

syed kamruzzaman
syed kamruzzaman

Posted on

Simple Nodejs MC Pattern

There are a lot of MC Pattern you can find on google.
Today, I am talking about my favorite MC Pattern. I am also PHP developer. PHP one of the most popular Frameworks is Laravel. I am fond of Larevel MVC Pattern.
When I am building any project, trying to follow Laravel MVC Pattern.

let's do my Favourite MC pattern.

Prerequisites
Before we move on, you’ll need to have the following:

  1. Node.js installed on your machine.
  2. setup mongoDB on you computer.

Step-1
Create a Database on your MongoDB and also collection name.

Image description

Step-2
open your cmd terminal and type npm init -y
and install following package.

  1. express
  2. mongoose
  3. body-parser
  4. mongoose
  5. nodemon
"dependencies": {
    "body-parser": "^1.20.0",
    "express": "^4.17.3",
    "mongoose": "^6.3.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
Enter fullscreen mode Exit fullscreen mode

go to https://www.npmjs.com/ site and find out this package.

Step-3
following file structure do I have

Image description

Step-4
Create a new file index.js into routes folder [src/routes/index.js] and write this code.

const express = require('express');

const route = (app)=>{
    //unknowen route
    app.use('*', (req, res)=> res.status(404).json({status:"fail", data:"Route does not exist"}));
}

module.exports = route;
Enter fullscreen mode Exit fullscreen mode

Step-4
Now go to app.js file and write this code

const express = require('express');
const route = require('./src/routes/index');
const dbConnection = require('./src/utils/dbConnection');
const bodyParse = require('body-parser');

const app = new express();
//use app
app.use(bodyParse.json());
app.use(bodyParse.urlencoded({ extended: true }));

//mongoose DB connnection
dbConnection();
//Route connect
route(app);

module.exports = app;
Enter fullscreen mode Exit fullscreen mode

Step-5
We are just ending basic setup. First go to dbConnection.js file [src/utils/dbConnection.js] and write-

const mongoose = require('mongoose');


const dbConnection = async () =>  {
      const URI  = await "mongodb://localhost:27017/mongoose_query_pattern";
      mongoose.connect(URI,
        err => {
            if(err) throw err;
            console.log('connected to MongoDB')
        });

}

module.exports = dbConnection;
Enter fullscreen mode Exit fullscreen mode

then go to index.js [root index] file and write this code

const app = require('./app');


app.listen(5000,function () {
    console.log("This Server is running from 5000 port")
});
Enter fullscreen mode Exit fullscreen mode

Ok, now finished our basic setup. Open your Terminal and type nodemon index.js. if all is ok then showing as the image.

Image description

Now our database connection is ok and run our app successfully. Lets do MC Pattern

Step-6
Create userRouterApi.js file on routes folder. [src/routes/userRouterApi.js] and write this

const express = require('express');
const UserController = require('../controllers/UserController');
const router = express.Router();

router.get('/test-user-api', UserController.testUser)

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Step-7
Create another file, name is UserController.js on controllers folder [src/controllers/UserController.js] and write this

module.exports = class UserController{

        static testUser = async(req, res)=>{

            try{

                return res.status(200).json({
                  code: 200,
                  message: "Test User api call",
                  data: "Test User api call",
                });

            }catch(error){
              res.status(501).json({
                code: 501,
                message: error.message,
                error: true,
              });
            }
        }

}
Enter fullscreen mode Exit fullscreen mode

Step-8
Now go to index.js file which is located on routes folder [src/roues/index.js] and write this

const express = require('express');
const userRouterApi = require('./userRouterApi');

const route = (app)=>{

    //All user router 
    app.use('/api/v1', userRouterApi);

    //unknowen route
    app.use('*', (req, res)=> res.status(404).json({status:"fail", data:"Route does not exist"}));
}
module.exports = route;
Enter fullscreen mode Exit fullscreen mode

Now, you have done user controller first route. which is

http://localhost:5000/api/v1/test-user-api

if you open your postman and run this URL. you can see below this output

Image description

this project you can see also another folder. Like as middlewares, models, repositories and utils.

middlewares folder- you can write any middleware related code.
models folder- you can write all models in this folder.
repositories folder - if you know about repository pattern, then your code will be well structure. Another day I will talking about repository pattern
utils folder - all Extra function, like as jwt, authentication, databaseConncetion etc. you can add this folder.

That's all. Happy Learning :) .
[if it is helpful, giving a star to the repository 😇]
https://github.com/kamruzzamanripon/simple-node-mc-pattern

Top comments (0)