Skip to content

Commit ef87f1c

Browse files
committed
댓글삭제,유효성체크 추가
1 parent 6015828 commit ef87f1c

File tree

3 files changed

+87
-16
lines changed

3 files changed

+87
-16
lines changed

models/ProductsModel.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ var autoIncrement = require('mongoose-auto-increment');
44

55
//생성될 필드명을 정한다.
66
var ProductsSchema = new Schema({
7-
name: String, //제품명
7+
name: {//제품명
8+
type: String,
9+
required: [true, '제목을 입력해주세요']
10+
},
811
price: Number, //가격
912
description: String, //설명
1013
created_at: { //작성일

routes/admin.js

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,26 +24,36 @@ router.get('/products/write', function (req, res) {
2424
});
2525

2626
router.post('/products/write', function (req, res) {
27-
var product = new ProductsModel({//mongoose에서 insert하는 방식:key field 일치 시켜주기
27+
var product = new ProductsModel({
2828
name: req.body.name,
2929
price: req.body.price,
3030
description: req.body.description,
3131
});
32-
product.save(function (err) {//DB에 저장,
33-
res.redirect('/admin/products');//새로고침시 다시 저장될 수 있으니 save button 클릭시 list페이지로 이동
34-
});
32+
var validationError = product.validateSync();
33+
if (validationError) {
34+
res.send(validationError);
35+
} else {
36+
product.save(function (err) {
37+
res.redirect('/admin/products');
38+
});
39+
}
3540
});
3641

37-
//제품 상세 페이지
42+
//제품 상세 페이지//콜백 3개
3843
router.get('/products/detail/:id', function(req, res){
3944
//url 에서 변수 값을 받아올떈 req.params.id 로 받아온다
4045
ProductsModel.findOne({'id': req.params.id},function(err, product){//findOne(조건,콜백함수)는 한 줄의 데이터만 가져와
41-
res.render('admin/productsDetail', {product:product});
46+
//res.render('admin/productsDetail', {product:product});
47+
CommentsModel.find({ product_id: req.params.id }, function (err, comments) {
48+
res.render('admin/productsDetail',
49+
{product : product, comments : comments });
50+
});
4251
});
4352
});
4453

4554
//제품 수정 페이지
4655
router.get('/products/edit/:id',function(req,res){
56+
//기존에 폼에 value안에 값을 셋팅하기 위해서 만든다.
4757
ProductsModel.findOne({'id': req.params.id},function(err, product){//
4858
res.render('admin/form',{product:product});
4959
});
@@ -71,6 +81,26 @@ router.get('/products/delete/:id',function(req,res){
7181
});
7282
});//require로 따로 뺄 수 있어
7383

84+
//댓글 기능
85+
router.post('/products/ajax_comment/insert',function(req,res){
86+
var comment = new CommentsModel({
87+
content: req.body.content,
88+
product_id: parseInt(req.body.product_id)
89+
});
90+
comment.save(function(err,comment){
91+
res.json({
92+
id : comment.id,
93+
content : comment.content,
94+
message : "success"
95+
});
96+
});
97+
});
7498

99+
//댓글 삭제 기능
100+
router.post('/products/ajax_comment/delete', function (req, res) {
101+
CommentsModel.remove({ id: req.body.comment_id }, function (err) {
102+
res.json({ message: "success" });
103+
});
104+
});
75105

76106
module.exports = router;

views/admin/productsDetail.ejs

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,32 @@
1313
<%=product.getDate.month%>
1414
<%=product.getDate.day%>
1515
</div>
16-
16+
1717
<%=product.description%>
1818

19+
<!-- 댓글영역 -->
20+
<hr />
21+
<div id="comment_area">
22+
<% comments.forEach( function(comment){ %>
23+
<div>
24+
<%=comment.content%>
25+
[<a class='comment_delete' comment_id='<%=comment.id%>'>삭제</a>]
26+
</div>
27+
<%});%>
28+
</div>
1929

20-
</div>
30+
2131
<div>
22-
댓글작성하기
32+
<br><b>댓글작성하기</b>
2333
<form id="commentForm" action="" method="post">
2434
<input type="hidden" name="product_id" value="<%=product.id%>" />
2535
<textarea class="form-control" name="content"></textarea>
2636
<button class="btn btn-primary" style="margin-top: 10px">댓글작성</button>
2737
</form>
2838
</div>
29-
<!-- 댓글영역 -->
39+
</div>
40+
41+
3042
</div>
3143

3244
<!-- 댓글영역 -->
@@ -35,7 +47,7 @@
3547
<a href="/admin/products" class="btn btn-default">목록으로</a>
3648
<a href="/admin/products/edit/<%=product.id%>" class="btn btn-primary">수정</a>
3749

38-
50+
<!--ajax client부분-->
3951
<script>
4052
$(document).ready(function(){
4153
$('#commentForm').submit(function(){
@@ -49,18 +61,44 @@
4961
data: $(this).serialize(),//serialize: 각 데이터들을 mapping을 해주는 함수
5062
})
5163
.done(function(args){
52-
console.log(args);
64+
if(args.message==="success"){
65+
$('#comment_area').append(
66+
//댓글추가시 삭제버튼도 같이 생기도록
67+
'<div>'+args.content+
68+
"[<a class='comment_delete' comment_id='"+ args.id+"'>삭제</a>] </div>"
69+
);
70+
$('#commentForm textarea[name=content]').val("");
71+
}
72+
//console.log(args);//message 하나만 출력
5373
})
5474
.fail(function(args){
5575
console.log(args);
5676
});
57-
}
58-
else{
77+
}else{
5978
alert("댓글 내용을 입력해주세요.");
6079
}
6180
return false;
62-
});
81+
});
82+
});
83+
84+
$(document).on('click','.comment_delete',function(){
85+
if(confirm('삭제하시겠습니까?')){
86+
var $self =$(this); //여기서 this는 해당 댓글의 <a>태그를 뜻함
87+
$.ajax({
88+
url: '/admin/products/ajax_comment/delete',
89+
type: 'POST',
90+
data: {comment_id : $self.attr('comment_id')},//변수의 attribute로 접근
91+
});
92+
.done(function(){
93+
$self.parent().remove();//<a>태그의 parent니까 <div>
94+
alert("삭제가 완료되었습니다.");
95+
})
96+
.fail(function(args){
97+
console.log(args);
98+
});
99+
}
63100
});
101+
64102
</script>
65103

66104

0 commit comments

Comments
 (0)