지난포스트 (deprecated)/NodeJS (deprecated)

Node.js + Express + MongoDB CRUD 만들기

.log('FE') 2018. 12. 28. 18:57
728x90
반응형

 

 

 

 

 

1단계 프로젝트 생성

 

 

  • Install Node.js
  • Install MongoDB
  • # npm install express-generator -g // express 설치
  • # express -h // 명령의 옵션 확인
  • # express crud-example --view=ejs // crud-example폴더 생성 ejs템플릿 사용
  • # cd crud-example && npm install // 폴더이동 node 모듈 설치
  • # npm install mongoose --save // 해당 프로젝트에 의존하는 mongoose 모듈 설치
  • # mongo // MongoDB 서버 실행
  • # robomongo 설치 // 데이터베이스 관리도구 설치
  •  # npm start
  • localhost:3000 접속


 

 app.js 코드 추가

 

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;


mongoose.connect('mongodb://localhost:27017/local')
.then(() => console.log('connected successful'))
.catch((err) => console.error(err));

 

 

  • # npm install -g nodemon // MopngoDB서버연결 콘솔에서 실시간 확인
  • # nodemon // nodemon 실행

 

 

 

 

 

2단계 Schema Model 만들기

 

/models/Employee.js

 

var mongoose = require('mongoose');


var EmployeeSchema = new mongoose.Schema({
name: String,
address: String,
position: String,
salary: Number,
updated_at : {type: Date, default: Date.now},
});


module.exports = mongoose.model('Employee', EmployeeSchema);

 

Employee 데이터에 대한 모델을 작성합니다.

DB 에 local > Collections > employees 에 name, address, position, salary, updated_at 의 테이블이 생성됩니다.

 

 

 

 

 

3단계 CRUD 컨트롤러 생성

 

/controllers/EmployeeController.js

 

var Employee = require("../models/Employee");
var employeeController = {};




// 전체 직원 목록 보기
employeeController.list = function(req, res) {
Employee.find({}).exec(function (err, employees) {
if(err) {
console.log(`Error: ${err}`);
} else {
res.render("../views/employees/index", {employees: employees});
}
});
};


// id 로 단일 직원 표시
employeeController.show = function(req, res) {
Employee.findOne({_id: req.params.id}).exec(function(err, employee) {
if(err) {
console.log(`Error: ${err}`);
} else {
res.render("../views/employees/show", {employee: employee});
}
})
}


// 직원추가
employeeController.create = function(req, res) {
res.render("../views/employees/create");
};


// 직원 저장
employeeController.save = function(req, res) {
var employee = new Employee(req.body);


employee.save(function(err) {
if(err) {
console.log(err);
res.render("../views/employees/create");
} else {
console.log("Successfully create an employee");
res.redirect(`/employees/show/${employee._id}`);
}
});
};



// 직원 편집
employeeController.edit = function(req, res) {
Employee.findOne({_id: req.params.id}).exec(function(err, employee) {
if(err) {
console.log(`Error : ${err}`);
} else {
res.render("../views/employees/edit", {employee: employee});
}
});
};



// 편집된 직원 업데이트
employeeController.update = function(req, res) {
Employee.findByIdAndUpdate(
req.params.id, { $set:
{
name: req.body.name,
address: req.body.address,
position: req.body.position,
salary: req.body.salary}
},
{new: true}, function(err, employee) {
if(err) {
console.log(err);
res.render("../views/employees/edit", {employee: req.body});
} else {
res.redirect(`/employees/show/${employee._id}`);
}
});
};


// 단일 직원 데이터 제거
employeeController.delete = function(req, res) {
Employee.remove({_id:req.params.id}, function(err) {
if(err) {
console.log(err);
} else {
console.log("Employee deleted!!");
res.redirect("/employees");
}
});
};


module.exports = employeeController;

 

/models/Employee.js 를 모듈로 불러오고

컨트롤러 객체를 생성한다.

 

그리고 각각 list, show, create, save, edit, update, delete 를 컨트롤러에 추가해준다.

 

list 에는 디비에 등록된 전체 직원의 목록을 보여주게되고

show 는 등록된 개별적인 직원에 대한 상세정보를 보여준다.

create 는 직원을 새롭게 추가하기위한것이고

save 는 별도의 페이지 없이 저장 처리후 show 페이지로 redirect 해준다.

edit 는 저장된 직원목록을 수정하는 페이지이고

update 는 수정한 직원정보를 update 하여 저장처리하게된다.

delete 는 등록된 직원 정보를 디비에서 제거하게된다.

 

 

4단계 Router 만들기

 

/routes/employees.js

 

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


var employee = require('../controllers/EmployeeController.js');


router.get('/', employee.list);


router.get('/show/:id', employee.show);


router.get('/create', employee.create);


router.post('/save', employee.save);


router.get('/edit/:id', employee.edit);


router.post('/update/:id', employee.update);


router.post('/delete/:id', employee.delete);


module.exports = router;

 

 

 

express 모듈을 불러오고 Router() 메서드를 변수에 저장한다.

 

방금 생성한 컨트롤러 모듈을 불러오고

 

각 라우터 별로 컨트롤러를 지정해 준다.

 

app.js

 

var employees = require('./routes/employees');
app.use('/employees', employees); 



 

 

5단계 ViewPage 생성

 

/views/employees/index.ejs

/views/employees/create.ejs

/views/employees/edit.ejs

/views/employees/show.ejs

 

save, update, delete 는 처리만 진행하기 때문에 별도의 페이지가 없습니다. 처리가 완료되면 redirect 된 url 로 이동하게 됩니다.

 

/views/employees/index.ejs

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Index Page</title>
</head>
<body>
<div class="container">
<h3><a href="/employees/create">Create Employee</a></h3>
<h1>Employee List</h1>
<% if(employees.length > 0) { %>
<table>
<thead>
<tr>
<th>Employee Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<% for(var i = 0; i < employees.length; i++) { %>
<tr>
<td>
<a href="/employees/show/<%= employees[i]._id %>">
<%= employees[i].name %>
</a>
</td>
<td><%= employees[i].position %></td>
</tr>
<% } %>
</tbody>
</table>
<% } else { %>
<div>No Employees found.</div>
<% } %>
</div>
</body>
</html>

 

 

/views/employees/create.ejs

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Create Employee</title>
</head>
<body>
<div class="container">
<h3><a href="/employees">Employee List</a></h3>
<h1>Create New Employee</h1>
<form action="/employees/save" method="post">
<table>
<tbody>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="address"></textarea></td>
</tr>
<tr>
<td>Position</td>
<td><input type="text" name="position"></td>
</tr>
<tr>
<td>Salary</td>
<td><input type="number" name="salary"></td>
</tr>
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>

 

/views/employees/edit.ejs

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Edit Employee</title>
</head>
<body>
<div class="container">
<h3><a href="/employees">Employee List</a></h3>
<h1>Edit Employee</h1>
<form action="/employees/update/<%= employee._id %>" method="post">
<table>
<tbody>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" value="<%= employee.name%>" />
</td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="address">
<%= employee.address %>
</textarea>
</td>
</tr>
<tr>
<td>Position</td>
<td>
<input type="text" name="position" value="<%= employee.position %>">
</td>
</tr>
<tr>
<td>Salary</td>
<td>
<input type="number" name="salary" value="<%= employee.salary %>">
</td>
</tr>
<tr>
<td><button type="submit">Update</button></td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>

 

 

/views/employees/show.ejs

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Show List</title>
</head>
<body>
<div class="container">
<h3><a href="/employees">Employee List</a></h3>
<h1>Employee Detail</h1>
<table>
<tbody>
<tr>
<td>Name</td>
<td>:</td>
<td><%= employee.name %></td>
</tr>
<tr>
<td>Address</td>
<td>:</td>
<td><%= employee.address%></td>
</tr>
<tr>
<td>Position</td>
<td>:</td>
<td><%= employee.position %></td>
</tr>
<tr>
<td>Salary</td>
<td>:</td>
<td><%= employee.salary %></td>
</tr>
</tbody>
</table>
<h3><a href="/employees/edit/<%= employee._id %>">EDIT</a></h3>
<form action="/employees/delete/<%= employee._id %>" method="post">
<button type="submit">DELETE</button>
</form>
</div>
</body>
</html>

 

 

 

 

code-reading 블로그에 방문해 주셔서 환영합니다.
댓글은 모두 환영하니 많이 달아주세요.

 

 

 

728x90
반응형