Contact Me

Node Js tutorial | CRUD

If don't have a clear idea about Mongodb basic query yet, Then my suggestion is first try to understand about Mongodb basic operation here MongoDB Basiuc CRUD Operation or MongoDB Basiuc

Lets go and see how to create a node.js API step by step

1. Create package.json

  1. Create a new folder on desktop
  2. Open your terminal for Mac or CMD for Windows
  3. Go to the folder (Type cd Desktop then cd Folder Name)
  4. Type: npm init for save all dependency in the package.json file.
  5. Package name:Your package name here...
  6. Set package version or just press enter
  7. Put some description here
  8. Set the entry point here like: app.js or just press enter
  9. Test command: Just press enter
  10. Git repository: Just press enter
  11. Keyoards: Press enter or type the dependency name like (Express BodyParser etc)
  12. author: Type your name
  13. License: Just press enter
  14. Is this ok>: Just press enter
  15. Now you can able to see the output below

{
    "name": "testapi",
    "version": "1.0.0",
    "description": "This is test API",
    "main": "app.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node app.js"
    },
    "keywords": [
        "Express",
        "BodyParser"
    ],
    "author": "Al Imran",
    "license": "ISC"
}   

2. Add the dependencies into the package.json file

  1. Open package.json file with any text editor
  2. Set the dependencies name under the license
  3. Now see the package.json file after including the dependencies

{
    "name": "testapi",
    "version": "1.0.0",
    "description": "This is test API",
    "main": "app.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node app.js"
    },
    "keywords": [
        "Express",
        "BodyParser"
    ],
    "author": "Al Imran",
    "license": "ISC",
    "dependencies": {
        "express": "*",
        "body-parser": "*"
    }
}     

3. NPM Install

  1. Open your terminal for Mac or CMD for Windows
  2. Go to the project folder (Type cd Desktop then cd Folder Name)
  3. Type: npm install
  4. After complete the install you can see the node_modules folder into the project folder

npm install

4. Node server

  1. Create new file root of the folder app.js
  2. node server
  3. Open app.js file with any text editor
  4. Coppy and past the code below in the app.js
  5. app.js code

    const express = require("express");
    const bodyParser = require("body-parser");
    const app = express();
    
    app.get('/',function(req, res){
        res.send({"message":"Welcome to the Node.Js PAI"});
    });
    
    const port= 2003;
    app.listen(port, function(){
        console.log("Server start on port", port)
    });
    
  6. Go to the terminal and run the server by the comment npm start
  7. Watch your terminal. If server start successfully you can see like this output Server start on port 2003 in your terminal
  8. Then Go to your browser and type http://localhost:2003/
server_output

5. Node js database connection

If everything is ok successfully start the node js App, then let's go and see step by step how to connect the database

  1. Create a new folder called config root of the app directory
  2. Node js database connection
  3. Then create a new js file into the config folder called db.config.js for connect the database
  4. db_config_file
  5. In the db.config.js file paste the code below for connected database
  6. db.config.js code

    module.exports={
        database:'mongodb://localhost:27017/meanauth2'
    }
    
  7. Now go to the app.js file configure the database. For that paste the code above the line const app = express();
  8. db.config.js code

    const cors=        require('cors');
    const mongoose=    require('mongoose');
    const config= require('./config/db.config');
    mongoose.connect(config.database);
    
  9. Now Paste the code below under the line mongoose.connect(config.database); for database connections test.
  10. db.config.js code

    mongoose.connection.on('connected', function(){
    console.log("Successfully connect to the database :", config.database)
    });
    
    mongoose.connection.on('error', function(){
    console.log("Could not connect to the database, Exist now...");
    process.exit()
    })
    
  11. If everything is ok then go to root of the folder and create another new folder calledapp
  12. Nodejs_API_App_Folder
  13. And then create another 3 folder in the app folder like: controllers,models and routes
  14. Nodejs_API_App_function_Folder
  15. Now go to the routes folder and create a js file called: employ.route.js. Then open theemploy.route.js file and add some route function. Code will be look like below.
  16. employ_route

    employ.route.js code

    const express = require('express');
    const router = express.Router();
    
    router.get('/create', function(req, res){
        res.json("Create Employ Route is working successfully!")
    })
    router.get('/read', function(req, res){
        res.json("Read Employ Route is working successfully!")
    })
    router.get('/update', function(req, res){
        res.json("Uupdate Employ Route is working successfully!")
    })
    router.get('/delete', function(req, res){
        res.json("Delete Employ Route is working successfully!")
    })
    module.exports = router;
    
  17. And then go to the app.js file and register the router. For that paste the code below under the line const app = express();
  18. app.js code

    const employ = require('./app/routes/employ.route');
    
  19. If don't use CORS Middleware yeat, please add the Middleware under the line const employ = require('./app/routes/employ.route');
  20. app.js code

    app.use(cors());
    
  21. Then install the CORS Middleware by the command npm install cors --save and
  22. Install the mongoose ORM by the command npm install mongoose --save
  23. Then use bodyParser Middleware for return data as json. Add the code below under the app.use(cors());
  24. app.js code

    app.use(bodyParser.json());
    app.use('/employ', employ)
    
  25. Finally app.js file will be look like below
  26. app.js code

    const express=     require('express');
    const bodyParser=  require('body-parser');
    const cors=        require('cors');
    const mongoose=    require('mongoose');
    
    //Configuring the database
     const config= require('./config/db.config');
     mongoose.connect(config.database);
    
     //Database connections check
     mongoose.connection.on('connected', function(){
         console.log("Successfully connect to the database :", config.database)
     });
     mongoose.connection.on('error', function(){
         console.log("Could not connect to the database, Exist now...");
         process.exit()
     })
     
    //create express
    const app = express();
    
    const employ = require('./app/routes/employ.route');
    
    //CORS Middleware
    app.use(cors());
    
    // parse requests of content-type - application/json
    app.use(bodyParser.json());
    app.use('/employ', employ)
    
    //Index route
    app.get('/',function(req, res){
        res.send({"message":"Welcome to the MEAN App"});
    });
    
    //Start server
    //const port= 2002;
    const port= process.env.PORT || 2003;
    app.listen(port, function(){
        console.log("Server start on port", port)
    });
    
    
  27. Then go to your browser and test the abode route. It's look like below
  28. CRUD Route

    a. http://localhost:2003/
    b. http://localhost:2003/employ/create
    c. http://localhost:2003/employ/read
    d. http://localhost:2003/employ/update
    e. http://localhost:2003/employ/delete
    
  29. If all route is working good then lets go now and see the CRUD operations in mongodb database.
  30. First we have need to create our employ data structure/schema. And for that go app > models folder
  31. Create a js file called employ.models.js and paste the example schema below and include or exclude yourself
  32. employ_models_schema

    Employ Schema Models

    const mongoose = require('mongoose');
    const employSchema = mongoose.Schema({
        name:{type:String, require:true},
        emp_Id:{type:String, require:true, unique:true},
        email:{type:String},
        address:{type:String}
    },{
        timestamp:true
    });
    const Employ = module.exports = mongoose.model('Employ', employSchema);
    
  33. Then go to the app > controllers folder.
  34. Create a js file called employ.controller.js and paste the function below for save/create employ data into the mongodb.
  35. employ.controller

    Employ Controller

    const Employ = require('../models/employ.models');
    module.exports.create = function(req, res){
        let createEmp = new Employ({
            name: req.body.name,
            emp_Id: req.body.emp_Id,
            email: req.body.email,
            address: req.body.address,
        });
        createEmp.save({W:1}, function(err, results){
            if(err){
                res.json({success: false, msg:"Fail to add employ!"})
            }else{
                res.status(200);
                //res.json({success: true, msg:'Employ added successfully'});
                res.json({msg:results});
            }
        })
    }
    
  36. Then go to the app > route folder and import the employ controller file below
  37. const employ = require('../controllers/employ.controller');
    
  38. And then change the first route method get to post and function like below.
  39. Employ Route

    //Previus Route:
    router.get('/create', function(req, res){
        res.json("Create Employ Route is working successfully!")
    })
    
    //Replace the above route by this below:
    router.post('/create', employ.create);
    
  40. And now we are going to check the insert operations. For that open your Postman select the POST method and paste the create route and select data into postman body section which field you define into your schema or flow the image below.
  41. mongodb-create
  42. Same the way flow the instructions below for READ, UPDATE And DELETE operations.
  43. For READ/GET data

    Add the function below under the create function into employ.controller.js for get/read data which you insert before:

    Employ Controller

    module.exports.read = function(req, res){
        Employ.find(function(err, results){
            if(err){
                res.status(500).json({err:err});
            }else{
                res.status(200).json({msg: results})
            }
        })
    };
    

    Update the route into the app > route folder:

    Employ Route

    //Previus Route:
    router.get('/read', function(req, res){
        res.json("Read Employ Route is working successfully!")
    })
    
    //Replace the above route by this below:
    router.get('/read', employ.read);
    

    And Chekc it by your Postman:

    Note: Before checking data, please open your terminal and go to root of the folder and install nodemon by the command below

    npm install nodemon --save
    
    mongodb-read

    For UPDATE data

    Add the function below under the read function for update data:

    Employ Controller

    module.exports.update = function(req, res){
        Employ.findById(req.body._id, function(err, results){
            if(err){
                res.status(500).json({errmsg: err});
            }else{
                results.name = req.body.name;
                results.emp_Id = req.body.emp_Id;
                results.email = req.body.email;
                results.address = req.body.address;
                results.save(function(err, results){
                    if(err){
                        res.status(500).json({errmsg: err});
                    }else{
                        res.status(200).json({msg: results});
                    }
                })
            }
        })
    };
    

    Update the route into the app > route folder:

    Employ Route

    //Previus Route:
    router.get('/update', function(req, res){
        res.json("Uupdate Employ Route is working successfully!")
    })
    
    //Replace the above route by this below:
    router.put('/update', employ.update);
    

    And Chekc it by your Postman:

    mongodb-update

    For DELETE data

    Add the function below under the update function for delete data:

    Employ Controller

    module.exports.delete = function(req, res){
        Employ.findByIdAndRemove({_id: req.params.id}, function(err, results){
            if(err){
                res.status(500).json({errmsg: err});
            }else{
                res.status(200).json({msg: results});
            }
        })
    }
    

    Update the route into the app > route folder:

    Employ Route

    //Previus Route:
    router.get('/update', function(req, res){
        res.json("Uupdate Employ Route is working successfully!")
    })
    
    //Replace the above route by this below:
    router.delete('/delete/:id', employ.delete);
    

    And Chekc it by your Postman:

    mongodb-update

If everything is ok and you are interasted to se how to implementing this API in Angular front-end then please see the MEAN APPLICATIONS page or click the Next button below

Next

Contact

Md. Al Imran Islam
(Software Engineer)

imran.meanstack@gmail.com

meanstackfundamental.com

Al-imran

01751888673