Nodejs Mongodb Crud

By ukmodak | April 29th 2021 06:09:08 AM | viewed 578 times

After install nodejs create a server file crudExpressProject/app.js in the root folder crudExpressProject and add the following code


 // start mongo database connection  
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/ukdb',{useUnifiedTopology: true,useNewUrlParser: true });

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connectionasdf error:'));

db.once('open', function() {
    console.log("Successfully connected to MongoDB!");
});

 // end database connection 


 // start server configuration 
 
const express = require('express');
const bodyParser = require('body-parser');// initialize our express app
const app = express();
const path = require('path');

// end server configuration  


const product = require('./routes/product.route'); // Imports routes for the products
const user = require('./routes/user.route'); // Imports routes for the products


// Static Files

app.use(express.static('public'));
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use('/img', express.static(__dirname + 'public/images'))
app.use('/static',express.static(path.join(__dirname, 'public')));

// Set View's

app.set('views', './views');
app.set('view engine', 'ejs').renderFile;



app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//app.use(expressValidator());




   // setup controller path base on route constant 
app.use('/products', product);
app.use('/users', user);


let port = 1234;

app.listen(port, () => {
    console.log('Server is up and running on port numner ' + port);
});

create the following folder crudExpressProject/routes and add the following files:


user.route.js =>

const express = require('express');
const router = express.Router();

const user_controller = require('../controllers/user.controller');
//const validator = require('../src/validation.js');



router.get('/new', user_controller.new);
router.get('/admin_regi', user_controller.admin_regi);
//router.route('/admin_regi_add').post(validator.publicRouteValidate('admin_regi_add'),user_controller.admin_regi_add);
router.post('/admin_regi_add',user_controller.admin_regi_add);
router.get('/admin_login', user_controller.admin_login);



module.exports = router;

product.route.js =>

const express = require('express');
const router = express.Router();

   // setup the controller constant
const product_controller = require('../controllers/product.controller');


   // setup controller method path base on controller constant 
router.get('/test', product_controller.test);
router.post('/create', product_controller.product_create);
router.get('/:id', product_controller.product_details);
router.put('/:id/update', product_controller.product_update);
router.delete('/:id/delete', product_controller.product_delete);

module.exports = router;

create the following folder crudExpressProject/controllers and add the following files:

user.controller.js =>

const User = require('../models/user.model');   // add the product models 
const path = require('path');
const multer = require('multer');
const FileUploadLib = require('../src/fileupload_lib.js');  // add the upload lib file from  src folder



const { check, validationResult } = require('express-validator');

exports.new = function (req, res) {
    res.render('user/new',{ text: 'Hey Uzzal' });
};


exports.admin_regi = function (req, res) {
    res.render('user/admin_regi');    // set the view  user/admin_regi.ejs 
};

exports.admin_regi_add = function (req, res) {

    console.log("uk body"+req.body)
    const  fname = req.body.fullname;
    //const  filename = req.file.filename;


    /*  upload file  */
    let upload = multer({
        storage: FileUploadLib.storage,
        //limits : {fileSize : 1000000},
        limits : FileUploadLib.profixeSize,
        fileFilter:FileUploadLib.profilePicFilter
    }).single("profile_pic");

    upload(req, res, (err) => {

        if(!req.body.fullname) {
            return res.status(400).send({
                message: "Fullname can not be empty"
            });
        }else if(!req.body.email){
            return res.status(400).send({
                message: "email can not be empty"
            });
        }else if(!req.body.mobile){
            return res.status(400).send({
                message: "mobile can not be empty"
            });
        }
        /*  end validation   */

        const user = new User({
            user_type:req.body.user_type,
            fullname:req.body.fullname,
            mobile:req.body.mobile,
            email:req.body.email,
            password :req.body.pword,
            remember_token :'',
            create_date: Date.now(),
            update_date: '',
            active: 1,
            meta_name:req.body.email.split("@")[0]+Math.floor((Math.random() * 100) + 2),
            user_group_meta_name:'retailer',
            birth_date: Date.now(),
            sex:req.body.sex,
            prefer_contact:req.body.prefer_con,
            provider:'',
            provider_id: '',
            emp_dept: '',
            emp_desg: '',
            //picture:req.file.fieldname.toLowerCase().split(' ').join('-') + '-' + Date.now()+path.extname(req.file.originalname)
            picture:req.getFileName.fileName
        });

        user.save()
            .then(data => {
                res.send(data);
            }).catch(err => {
            res.status(500).send({
                message: err.message || "Some error occurred while creating user profile."
            });
        });


        if(err) {
            res.send(err);
        }

        //res.send(`You have uploaded this image: <hr/><img src="/static/images/profile/${req.file.filename}" width="500"><hr /><a href="./">Upload another image</a>`);
    });

    /*  validation   */

};

exports.admin_login = function (req, res) {
    res.render('user/admin_login');    // set the view  user/admin_login.ejs 
};

product.controller.js =>

const Product = require('../models/product.model');   // add the product models 

//Simple version, without validation or sanitation
exports.test = function (req, res) {
    res.send('Greetings from the Test controller!');
};

exports.product_create = function (req, res) {
    let product = new Product(
        {
            name: req.body.name,
            price: req.body.price
        }
    );

    product.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Product Created successfully')
    })
};

exports.product_details = function (req, res) {
    Product.findById(req.params.id, function (err, product) {
        if (err) return next(err);
        res.send(product);
    })
};

exports.product_update = function (req, res) {
    Product.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err, product) {
        if (err) return next(err);
        res.send('Product udpated.');
    });
};

exports.product_delete = function (req, res) {
    Product.findByIdAndRemove(req.params.id, function (err) {
        if (err) return next(err);
        res.send('Deleted successfully!');
    })
};

create the following folder crudExpressProject/models and add the following files:

user.model.js =>

const mongoose = require('mongoose');
const UserSchema = mongoose.Schema;


let UserTableSchema = new UserSchema({
    user_type: {type: String, required: true, max: 100},
    fullname: {type: String, required: true, max: 200},
    mobile: {type: String, required: true, max: 15},
    email: {type: String, required: true, max: 100},
    password : {type: String, required: true, max: 100},
    remember_token : {type: String, required: false, max: 100},
    create_date: {type: Date},
    update_date: {type: Date},
    active: {type: Number, required: true, max: 1},
    meta_name: {type: String, required: true, max: 150},
    user_group_meta_name: {type: String, required: true, max: 100},
    birth_date: {type: Date},
    sex: {type: String, required: true, max: 1},
    prefer_contact: {type: String, required: true, max: 100},
    provider: {type: String, required: false, max: 100},
    provider_id: {type: String, required: false, max: 100},
    emp_dept: {type: String, required: false, max: 150},
    emp_desg: {type: String, required: false, max: 150},
    picture: {type: String,required: false, max: 250}
});

module.exports = mongoose.model('User', UserTableSchema);



product.model.js =>

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let ProductSchema = new Schema({
    name: {type: String, required: true, max: 100},
    price: {type: Number, required: true},
});


// Export the model
module.exports = mongoose.model('Product', ProductSchema);

create a file in crudExpressProject/views/index.ejs and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <%- include('layout/public_head'); %>
</head>
<body class="container">

<header>
    <%- include('layout/public_header'); %>
</header>

<main>
    <div class="jumbotron">
        <h1>This is great</h1>
        <p>Welcome to templating using EJS</p>
		<img src="/static/images/cat.jpg" alt="cat">
    </div>
    <div class="bg">Hi Uzzal</div>
</main>

<footer>
    <%- include('layout/public_footer'); %>
</footer>

</body>
</html>


create the following folder crudExpressProject/views/layout and add the following files:

public_head.ejs =>


<meta charset="UTF-8">
<title>QRIUS</title>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/frontend.css">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/custom.css">
<link rel="stylesheet" href="/css/menustyle.css">

<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/jquery-ui.css" media="all">



<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>

<script>
    $(function() {
        jQuery(".uiPic" ).datepicker(
            {
                dateFormat: 'dd/mm/yy',
                changeYear:true,
                changeMonth:true,
                minDate:new Date(1920,0,0),
                maxDate:new Date(2015,0,0),
                yearRange: "1920:2015"
            }
        );
    });
</script>
public_logo_top.ejs =>

<section id="topsection" class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopadding5" >

  <div class="transparent-header-background" style="background-color:rgba(255, 255, 255, 1);" >
    div  class="top-area top-area-style-default top-area-alignment ukfloatleft">

    </div>
  </div>
</section>
<div class="cls"></div>
<section  class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopadding5 logobarbg">

  <div ng-controller="topMenuController" class="ukmcontainer nopadding5">
    <input type="hidden" name="_token" class="_token" value="">


    <div class="col-xs-12 col-sm-12 col-md-2 col-lg-2" align="center">
      <div class="img-responsive logo">

        <a href="#"><img class="logo img-responsive" src="/static/images/qrius.png"></a>
      </div>
    </div>
    <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4" align="left">
      <div align="center" class="regiUser">

         Login in user info

      </div>
    </div>

    <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">

      <form  action="" method="GET" >
        <div >
          <input type="hidden" class="form-control search_business_meta_name" value=""  name="mn">
          <input type="hidden" class="form-control search_cat_meta_name" value=""  name="cmn">
          <input type="text" class="srch-term searchWidth" placeholder="search by menu category" name="search" id="srch-term" >

        </div>
      </form>


    </div>
    <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 nopadding5">

      <ul class="nav" align="right">

        <li class="dropdown user user-menu">
          <a href="#" return="false"  ng-click="showBagList()">
            WISH LIST
            <span class="label label-warning" id="topMenuBagSts" ></span>
          </a>
        </li>




        <li class="showOrderDiv dropdown tasks-menu ">

          <a href="{{route('order/checko')}}">CART
            <span class="label label-danger" id="topMenuCartSts"></span>
          </a>
        </li>

        <li class="dropdown user user-menu">

          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            LOGIN INFO
          </a>

          <ul class="dropdown-menu ">
            <li class="user-header" align="center">
              <ul class="menu" align="center">

                <li><a data-toggle="modal" href="#authLogin" return="false" ><i class="fa fa-sign-in"></i>   Sign in</a></li>
                <li<a data-toggle="modal" href="#authRegi" return="false" ><i class="fa fa-user-plus"></i>   Sign up</a></li>

              </ul>


            </li>
          </ul>

        </li>
      </ul>

    </div>

  </div>
</section>
<div class="productList"></div>

<section id="mainmenusection" class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopadding5 noSearch">

  <div class="ukmcontainer nopadding5">

    <%- include('../layout/public_maintop_menu'); %>

  </div>



</section>
<div class="cls"></div>


public_maintop_menu.ejs =>

<section id="mainmenusection" class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopadding5 noSearch">
  <div class="ukmcontainer nopadding5">
    <div class="menu-container cls">
      <div class="menu" style="width:100%;float:left;">
        <a href="#" class="menu-mobile"></a>
        <ul style="float:left;">
          <li>
            <a href="http://localhost/qrious" class="active">  <span class="glyphicon glyphicon-home" aria-hidden="true"></a>
          </li>
          <li>
            <a href="http://localhost/qrious/product/new/grm/gm-qr/dhm/-whats-new" class="">  What's New</a>
          </li>
          <<i class="menu-dropdown-icon">
            <a href="http://localhost/qrious/product/catm/grm/gm-qr/dhm/-men" class="">  Men</a>
          </li>
          </li>
        </ul>
      </div>
    </div>
  </div>
</section>


public_footer.ejs =>


<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding" style="padding-left:0px; padding-right:0px;">

    <div class="footer-top footermargintop">

        <div class="ukmcontainer bottom_tmargin">

            

            <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 mobile_text_align nopadding">
                <div class="margintop">
                    <h4 class="abt"><a alt="QRIUS" href="https://www.qriusbd.com/cont/viewc/8/About Us">About Us</a></h4>

                    <h4 class="abt"><a alt="QRIUS" href="https://www.qriusbd.com/contact/contact">Contact Us</a></h4>

                    <h4 class="abt"><a alt="QRIUS" href="https://www.qriusbd.com/cont/viewc/32">Q-Rewards</a></h4>

                    <h4 class="abt"><a alt="QRIUS" href="https://www.qriusbd.com/cont/viewc/30">Shipping Terms</a></h4>

                    <h4 class="abt"><a alt="QRIUS" href="https://www.qriusbd.com/cont/viewc/38">Return & Exchange</a></h4>
                </div>

            </div>

            

            <div class="col-xs-12 col-sm-4 col-md-3 col-lg-3 mobile_text_align nopadding">
                <div class="widget inline-column widget_contacts container-fluid">
                    <h3 class="widget-title">Contact us</h3>

                    <div class="gem-contacts">Shimanto Shambhar,</div>

                    <div class="gem-contacts">8th Floor,</div>

                    <div class="gem-contacts">Road No.2,</div>

                    <div class="gem-contacts">Dhanmondi,Dhaka 1205</div>

                    <div class="gem-contacts-item gem-contacts-phone">Phone<b> :</b> +880 1887 222 333</div>

                    <div class="gem-contacts-item gem-contacts-email">Email : <a href="mailto:info@domain.tld">info.qrius@dekkolegacy.com</a></div>
                </div>
            </div>

            

            

            <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 mobile_text_align nopadding">
                <div id="mc4wp_form_widget-2" class="widget inline-column  widget_mc4wp_form_widget mobile_text_align">

                    <h3 class="widget-title">Outlets Location</h3>

                    <ul class="flink">
                        <li><a href="https://www.qriusbd.com/cont/viewstore/1">Banani</a></li>
                        <li><a href="https://www.qriusbd.com/cont/viewstore/2">Mirpur</a></li>
                    </ul>

                    <div class="icon-bar"><a class="facebook2" href="https://www.facebook.com/qriuslifestyle/" target="_blank">
					<i class="fa fa-facebook"> </i> </a> 
					<a class="linkedin2" href="https://www.linkedin.com/company/qrius-lifestyle" target="_blank">
					<i class="fa fa-linkedin"> </i> </a> 
					<a class="twitter2" href="https://twitter.com/QriusL" target="_blank">
					<i class="fa fa-twitter"> </i> </a>
					<a class="instagram2" href="https://www.instagram.com/qriuslifestyle/" target="_blank">
					<i class="fa fa-instagram"> </i> </a> 
					<a class="pinterest2" href="https://www.pinterest.com/qriuslifestyle/" target="_blank">
					<i class="fa fa-pinterest"> </i> </a></div>

                </div>
            </div>
            

            <div class="col-xs-12 col-sm-12 col-md-5 col-lg-5 mobile_text_align nopadding">

                <h3 class="widget-title">Pay with</h3>

                <div class="wpb_wrapper">
                    <p><img class="alignnone size-medium wp-image-16918" data-src="" src="/static/images/ssl.png"></p>
                </div>

            </div>
            

        </div>

    </div>
    <div class="cls"></div>
    <div class="footer-bottom">
        <div style="width:300px; margin:auto auto;">
            <div class="ukmcontainer bottom_fmargin" align="center">

                <div class="footer-site-info">2019 © <a href="#" target="_self">A Concern of <span style="color:red">DEKKO LEGACY GROUP</span> </a></div>
            </div>
        </div>
    </div>

    <script>
        // back to top button
        window.onscroll = function() {scrollFunction()};

        function scrollFunction() {
            if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
                document.getElementById("myBtn").style.display = "block";
            } else {
                document.getElementById("myBtn").style.display = "none";
            }
        }
        function topFunction() {
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;
        }
    </script>


</div>

create the following folder crudExpressProject/views/user and add the following files:

admin_login.ejs =>

<!DOCTYPE html>
<html lang="en">
<head>
    <%- include('../layout/public_head'); %>
</head>
<body>
<div class="wrapper" >
<header class="main-header cls" >
    <%- include('../layout/public_logo_top'); %>
</header>


<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5">
<div class="ukmcontainer" align="center">


    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls" >
    <div class="publicEmailLoginBox">
        <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5">

            <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5 margintopottom5">
                <h4 class="modal-title paddingtopbottom10">Login</h4>
            </div>


            <form method="POST" action="login" aria-label="Login">
                <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5 margintopottom5">
                    <label class="col-xs-12 colsm-12 col-md-4 col-lg-4 control-label">E-Mail Address</label>

                    <div class="col-md-6">
                        <input id="email" type="email" class="form-control" name="email" value="" required autofocus>
                    </div>
                </div>

                <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5 margintopottom5">
                    <label class="col-xs-12 colsm-12 col-md-4 col-lg-4 control-label">Password

                    <div class="col-md-6">
                        <input id="password" type="password" class="form-control" name="password" required>

                    </div>
                </div>

                <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5 margintopottom5">
                    <div class="col-xs-12 colsm-12 col-md-4 col-lg-4"></div>
                    <div class="col-xs-12 colsm-12 col-md-6 col-lg-6">
                        <div class="form-check"  align="left">
                            <input class="form-check-input" type="checkbox" name="remember" id="remember">

                            <label class="form-check-label" for="remember">
                                Remember Me
                            </label>
                        </div>
                    </div>
                </div>

                <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5 margintopottom5">
                    <div class="cls"> </div>
                    <div class="col-xs-12 colsm-12 col-md-4 col-lg-4"></div>
                    <div class="col-xs-12 colsm-12 col-md-6 col-lg-6">
                        <button type="submit" class="btn btn-sm btn-default">
                            Login
                        </button>

                        <a class="btn btn-link" href="route('password/forget')">
                            Forgot Your Password?
                        </a>

                    </div>

                </div>
                <div class="cls"> </div>
                <div class="col-xs-12 colsm-12 col-md-12 col-lg-12"> </div>



            </form>
        </div>
    </div>
    </div>

</div>
</div>


<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5">
    <%- include('../layout/public_footer'); %>
</div>

</div>
</body>
</html>


admin_regi.ejs =>

<!DOCTYPE html>
<html lang="en">
<head>
    <%- include('../layout/public_head'); %>

</head>
<body>

<div class="wrapper" >
<header class="main-header cls" >
    <%- include('../layout/public_logo_top'); %>
</header>


<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5">
<div class="ukmcontainer" align="center">


    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls" >
    <div class="publicEmailLoginBox2">
        <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5">

            <div class="col-xs-12 colsm-12 col-md-12 col-lg-12 nopadding5 margintopottom5">
                <h4 class="modal-title paddingtopbottom10">Registration</h4>
            </div>


            <form  action="/users/admin_regi_add" enctype="multipart/form-data" method="POST">
                <div ng-show="showForm" class="panel-body userRegiForm">

                    <div class=" col-xs-12 col-sm-6 col-md-6 col-lg-6">


                        <input type="hidden" name="user_type" value="admin">



                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label"> Full Name <span class="red">*</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">
                                <input type="text" class="form-control"  name="fullname" value="" >

                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">E-Mail<span class="red">*</label>

                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">
                                <input type="email" required="required"  class="form-control" name="email" value="">
                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label"> Mobile<span class="red">*</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">
                                <input type="text" pattern="^[(017)|(018)|(016)|(015)|(019)]{3}[0-9]{8}" required="required"  class="form-control" name="mobile" value="">
                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">Password*
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">
                                <input type="password" required="required"  class="form-control" name="pword" value="">
                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">Confirm Password<span class="red">*</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">
                                <input type="password" required="required"  class="form-control" name="cpword">
                            </div>
                        </div>



                    </div>
                    <div class=" col-xs-12 col-sm-6 col-md-6 col-lg-6">

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">Date of Birth</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">

                                <input type="text"  class="form-control uiPic" placeholder="dd/MM/YYYY"  name="birth" />

                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">Sex</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">

                                        <input type="radio"  name="sex" value="m" /><label>Male</label>
                                        <input type="radio"  name="sex" value="f" /><label>Female</label>

                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">Preferred Contact <span class="red">*</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">

                                    <input type="radio" name="prefer_con" value="email" /><label>Email</label>
                                    <input type="radio" name="prefer_con" value="mobile" /><label>Mobile</label>



                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5 margintopottom5">
                            <label class="col-xs-12 col-sm-12 col-md-5 col-lg-5 control-label">profile Picture <span class="red">*</label>
                            <div class="col-xs-12 col-sm-12 col-md-7 col-lg-7 nopadding5">

                                <input type="file" name="profile_pic" accept="image/*" class="form-control" />




                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5">

                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopadding5 gfmargintop" align="center">
                                <button type="bubmit"  class="btn btn-sm btn-default">
                                    Sign up
                                </button>

                            </div>
                        </div>



                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5">

                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 gfmargintop" align="center">

                                <a href="'/auth/facebook'" taget="_blank" class="btn btn-facebook">Sign up with  <i class="fa fa-facebook"></i></a> 
                                <a href="/auth/google'" taget="_blank" class="btn btn-google">Sign up with  <i class="fa fa-google"></i> </a>


                            </div>
                        </div>
                    </div>

                </div>

            </form>
        </div>
    </div>
    </div>

</div>
</div>


<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls nopadding5">
    <%- include('../layout/public_footer'); %>
</div>

</div>

</body>
</html>



new.js =>


<!DOCTYPE html>
<html lang="en">
<head>
    <%- include('../layout/public_head'); %>
</head>
<body class="container">

<header>
    <%- include('../layout/public_header'); %>
</header>

<main>
    <div class="jumbotron">
        <div class="container"><h1>Hello, the world!</h1></div>
    </div>
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 cls" style="border:1px solid red">
            <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4" style="border:1px solid black">
              <label>Id
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4" style="border:1px solid black">
                <input type="text" name="id" value="" class="form-control">
            </div>
        </div>

        <h1>This is user</h1>
        <p>Welcome to templating using EJS</p>
		<img src="/static/images/cat.jpg" alt="cat">

    <div class="bg">Hi Uzzal</div>
</main>

<footer>
    <%- include('../layout/public_footer'); %>
</footer>

</body>
</html>

Download the punlic folder and keep in the location crudExpressProject

Public

create the following folder crudExpressProject/src and add the following files:


fileupload_lib.js =>


const path = require('path');
const multer  = require('multer');

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './public/images/profile/');
    },
    filename: function (req, file, cb) {
        //const fileName = file.originalname.toLowerCase().split(' ').join('-');
        const fileName = file.fieldname.toLowerCase().split(' ').join('-') + '-' + Date.now()+path.extname(file.originalname);
        req.getFileName ={
            fileName:fileName
        }
        cb(null , fileName);
    }
});

const profilePicFilter = function (req, file, cb){
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
       cb(null, true);
    } else {
        cb(null, false);
        return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
};

const profixeSize ={fileSize : 1000000};

exports.profilePicFilter = profilePicFilter;
exports.storage = storage;
exports.profixeSize = profixeSize;


bONEandALL
Visitor

Total : 19487

Today :22

Today Visit Country :

  • United States
  • Germany
  • United Kingdom
  • India
  • Switzerland
  • Singapore
  • The Netherlands