master 74a11aee717b cached
9 files
9.9 KB
2.9k tokens
3 symbols
1 requests
Download .txt
Repository: CodAffection/Node.js-Expess-MongoDB-CRUD
Branch: master
Commit: 74a11aee717b
Files: 9
Total size: 9.9 KB

Directory structure:
gitextract_p4fz5p5v/

├── README.md
└── project/
    ├── controllers/
    │   └── employeeController.js
    ├── models/
    │   ├── db.js
    │   └── employee.model.js
    ├── package.json
    ├── server.js
    └── views/
        ├── employee/
        │   ├── addOrEdit.hbs
        │   └── list.hbs
        └── layouts/
            └── mainLayout.hbs

================================================
FILE CONTENTS
================================================

================================================
FILE: README.md
================================================
# Node.js-Expess-MongoDB-CRUD

Content discussed : 
 - Form Design 
 - Post Form Data into Node.js
 - Implemented Form Validation with mongoose model
 - Insert, Update and Delete with Node and MongoDB

## Get the Code

```
$ git clone https://github.com/CodAffection/Node.js-Expess-MongoDB-CRUD.git
$ cd Node.js-Expess-MongoDB-CRUD/project
$ npm install
```

 ## How it works ?
 
 :tv: Video tutorial on this same topic  
 Url : https://youtu.be/voDummz1gO0
 
<a href="http://www.youtube.com/watch?feature=player_embedded&v=voDummz1gO0
" target="_blank"><img src="http://img.youtube.com/vi/voDummz1gO0/0.jpg" 
alt="Video Tutorial for Node.js-Expess-MongoDB-CRUD" width="500" height="400" border="10" /></a>


| :bar_chart:               |  List of Tutorials   |   | :moneybag:           | Support Us                           |
|--------------------------:|:---------------------|---|---------------------:|:-------------------------------------|
| Angular                   |http://bit.ly/2KQN9xF |   |Paypal                | https://goo.gl/bPcyXW                |
| Asp.Net Core              |http://bit.ly/30fPDMg |   |Amazon   Affiliate    | https://geni.us/JDzpE                |
| React                     |http://bit.ly/325temF |   |
| Python                    |http://bit.ly/2ws4utg |   | :point_right:        | Follow Us                            |
| Node.js                   |https://goo.gl/viJcFs |   |Website               |http://www.codaffection.com          |
| Asp.Net MVC               |https://goo.gl/gvjUJ7 |   |YouTube               |https://www.youtube.com/codaffection  |
| Flutter                   |https://bit.ly/3ggmmJz|   |Facebook              |https://www.facebook.com/codaffection |
| Web API                   |https://goo.gl/itVayJ |   |Twitter               |https://twitter.com/CodAffection      |
| MEAN Stack                |https://goo.gl/YJPPAH |   |
| C# Tutorial               |https://goo.gl/s1zJxo |   |
| Asp.Net WebForm           |https://goo.gl/GXC2aJ |   |
| C# WinForm                |https://goo.gl/vHS9Hd |   |
| MS SQL                    |https://goo.gl/MLYS9e |   |
| Crystal Report            |https://goo.gl/5Vou7t |   |
| CG Exercises in C Program |https://goo.gl/qEWJCs |   |



================================================
FILE: project/controllers/employeeController.js
================================================
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Employee = mongoose.model('Employee');

router.get('/', (req, res) => {
    res.render("employee/addOrEdit", {
        viewTitle: "Insert Employee"
    });
});

router.post('/', (req, res) => {
    if (req.body._id == '')
        insertRecord(req, res);
        else
        updateRecord(req, res);
});


function insertRecord(req, res) {
    var employee = new Employee();
    employee.fullName = req.body.fullName;
    employee.email = req.body.email;
    employee.mobile = req.body.mobile;
    employee.city = req.body.city;
    employee.save((err, doc) => {
        if (!err)
            res.redirect('employee/list');
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("employee/addOrEdit", {
                    viewTitle: "Insert Employee",
                    employee: req.body
                });
            }
            else
                console.log('Error during record insertion : ' + err);
        }
    });
}

function updateRecord(req, res) {
    Employee.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
        if (!err) { res.redirect('employee/list'); }
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("employee/addOrEdit", {
                    viewTitle: 'Update Employee',
                    employee: req.body
                });
            }
            else
                console.log('Error during record update : ' + err);
        }
    });
}


router.get('/list', (req, res) => {
    Employee.find((err, docs) => {
        if (!err) {
            res.render("employee/list", {
                list: docs
            });
        }
        else {
            console.log('Error in retrieving employee list :' + err);
        }
    });
});


function handleValidationError(err, body) {
    for (field in err.errors) {
        switch (err.errors[field].path) {
            case 'fullName':
                body['fullNameError'] = err.errors[field].message;
                break;
            case 'email':
                body['emailError'] = err.errors[field].message;
                break;
            default:
                break;
        }
    }
}

router.get('/:id', (req, res) => {
    Employee.findById(req.params.id, (err, doc) => {
        if (!err) {
            res.render("employee/addOrEdit", {
                viewTitle: "Update Employee",
                employee: doc
            });
        }
    });
});

router.get('/delete/:id', (req, res) => {
    Employee.findByIdAndRemove(req.params.id, (err, doc) => {
        if (!err) {
            res.redirect('/employee/list');
        }
        else { console.log('Error in employee delete :' + err); }
    });
});

module.exports = router;

================================================
FILE: project/models/db.js
================================================
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/EmployeeDB', { useNewUrlParser: true }, (err) => {
    if (!err) { console.log('MongoDB Connection Succeeded.') }
    else { console.log('Error in DB connection : ' + err) }
});

require('./employee.model');

================================================
FILE: project/models/employee.model.js
================================================
const mongoose = require('mongoose');

var employeeSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required: 'This field is required.'
    },
    email: {
        type: String
    },
    mobile: {
        type: String
    },
    city: {
        type: String
    }
});

// Custom validation for email
employeeSchema.path('email').validate((val) => {
    emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return emailRegex.test(val);
}, 'Invalid e-mail.');

mongoose.model('Employee', employeeSchema);

================================================
FILE: project/package.json
================================================
{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4",
    "express-handlebars": "^3.0.0",
    "mongoose": "^5.3.4"
  }
}


================================================
FILE: project/server.js
================================================
require('./models/db');

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');

const employeeController = require('./controllers/employeeController');

var app = express();
app.use(bodyparser.urlencoded({
    extended: true
}));
app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');

app.listen(3000, () => {
    console.log('Express server started at port : 3000');
});

app.use('/employee', employeeController);

================================================
FILE: project/views/employee/addOrEdit.hbs
================================================
<h3>{{viewTitle}}</h3>

<form action="/employee" method="POST" autocomplete="off">
    <input type="hidden" name="_id" value="{{employee._id}}">
    <div class="form-group">
        <label>Full Name</label>
        <input type="text" class="form-control" name="fullName" placeholder="Full Name" value="{{employee.fullName}}">
        <div class="text-danger">
            {{employee.fullNameError}}</div>
    </div>
    <div class="form-group">
        <label>Email</label>
        <input type="text" class="form-control" name="email" placeholder="Email" value="{{employee.email}}">
        <div class="text-danger">
            {{employee.emailError}}</div>
    </div>
    <div class="form-row">
        <div class="form-group col-md-6">
            <label>Mobile</label>
            <input type="text" class="form-control" name="mobile" placeholder="Mobile" value="{{employee.mobile}}">
        </div>
        <div class="form-group col-md-6">
            <label>City</label>
            <input type="text" class="form-control" name="city" placeholder="City" value="{{employee.city}}">
        </div>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-info"><i class="fa fa-database"></i> Submit</button>
        <a class="btn btn-secondary" href="/employee/list"><i class="fa fa-list-alt"></i> View All</a>
    </div>
</form>

================================================
FILE: project/views/employee/list.hbs
================================================
<h3><a class="btn btn-secondary" href="/employee"><i class="fa fa-plus"></i> Create New</a> Employee List</h3>
<table class="table table-striped">
    <thead>
        <tr>
            <th>Full Name</th>
            <th>Email</th>
            <th>Mobile</th>
            <th>City</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        {{#each list}}
        <tr>
            <td>{{this.fullName}}</td>
            <td>{{this.email}}</td>
            <td>{{this.mobile}}</td>
            <td>{{this.city}}</td>
            <td>
                <a href="/employee/{{this._id}}"><i class="fa fa-pencil fa-lg" aria-hidden="true"></i></a>
                <a href="/employee/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"><i class="fa fa-trash fa-lg" aria-hidden="true"></i></a>
            </td>
        </tr>
        {{/each}}
    </tbody>
</table>

================================================
FILE: project/views/layouts/mainLayout.hbs
================================================
<!DOCTYPE html>

<html>

<head>
    <title>Node.js express mongDB CRUD</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body class="bg-info">
    <div class="row">
        <div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">
            {{{body}}}
        </div>
    </div>

</body>

</html>
Download .txt
gitextract_p4fz5p5v/

├── README.md
└── project/
    ├── controllers/
    │   └── employeeController.js
    ├── models/
    │   ├── db.js
    │   └── employee.model.js
    ├── package.json
    ├── server.js
    └── views/
        ├── employee/
        │   ├── addOrEdit.hbs
        │   └── list.hbs
        └── layouts/
            └── mainLayout.hbs
Download .txt
SYMBOL INDEX (3 symbols across 1 files)

FILE: project/controllers/employeeController.js
  function insertRecord (line 20) | function insertRecord(req, res) {
  function updateRecord (line 43) | function updateRecord(req, res) {
  function handleValidationError (line 75) | function handleValidationError(err, body) {
Condensed preview — 9 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (11K chars).
[
  {
    "path": "README.md",
    "chars": 2236,
    "preview": "# Node.js-Expess-MongoDB-CRUD\n\nContent discussed : \n - Form Design \n - Post Form Data into Node.js\n - Implemented Form V"
  },
  {
    "path": "project/controllers/employeeController.js",
    "chars": 2974,
    "preview": "const express = require('express');\nvar router = express.Router();\nconst mongoose = require('mongoose');\nconst Employee "
  },
  {
    "path": "project/models/db.js",
    "chars": 290,
    "preview": "const mongoose = require('mongoose');\n\nmongoose.connect('mongodb://localhost:27017/EmployeeDB', { useNewUrlParser: true "
  },
  {
    "path": "project/models/employee.model.js",
    "chars": 650,
    "preview": "const mongoose = require('mongoose');\n\nvar employeeSchema = new mongoose.Schema({\n    fullName: {\n        type: String,\n"
  },
  {
    "path": "project/package.json",
    "chars": 346,
    "preview": "{\n  \"name\": \"project\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"server.js\",\n  \"scripts\": {\n    \"test\": \"ech"
  },
  {
    "path": "project/server.js",
    "chars": 690,
    "preview": "require('./models/db');\n\nconst express = require('express');\nconst path = require('path');\nconst exphbs = require('expre"
  },
  {
    "path": "project/views/employee/addOrEdit.hbs",
    "chars": 1362,
    "preview": "<h3>{{viewTitle}}</h3>\n\n<form action=\"/employee\" method=\"POST\" autocomplete=\"off\">\n    <input type=\"hidden\" name=\"_id\" v"
  },
  {
    "path": "project/views/employee/list.hbs",
    "chars": 902,
    "preview": "<h3><a class=\"btn btn-secondary\" href=\"/employee\"><i class=\"fa fa-plus\"></i> Create New</a> Employee List</h3>\n<table cl"
  },
  {
    "path": "project/views/layouts/mainLayout.hbs",
    "chars": 642,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n    <title>Node.js express mongDB CRUD</title>\n    <link rel=\"stylesheet\" href=\"https://"
  }
]

About this extraction

This page contains the full source code of the CodAffection/Node.js-Expess-MongoDB-CRUD GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 9 files (9.9 KB), approximately 2.9k tokens, and a symbol index with 3 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!