Skip to content

Commit 4d9a52f

Browse files
committed
Mongoose virtual 변수 추가
1 parent d662e8e commit 4d9a52f

3 files changed

Lines changed: 18 additions & 3 deletions

File tree

models/ProductsModel.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,19 @@ var ProductsSchema = new Schema({
1313
}
1414
});
1515

16+
//virtual 변수는 호출되면 실행하는 함수
17+
// Object create 의 get과 set과 비슷함
18+
//set은 변수의 값을 바꾸거나 셋팅하면 호출
19+
// get은 getDate변수를 호출하는 순간 날짜 월일이 찍힌다.
20+
ProductsSchema.virtual('getDate').get(function () {
21+
var date = new Date(this.created_at);//this사용
22+
return {
23+
year: date.getFullYear(),
24+
month: date.getMonth() + 1,
25+
day: date.getDate()
26+
};
27+
});
28+
1629
// 1씩 증가하는 primary Key를 만든다
1730
// model : 생성할 document 이름
1831
// field : primary key , startAt : 1부터 시작 시작점을 정해준다.

routes/admin.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ router.get('/',function(req,res){
1111
//res.send("admin products");
1212
router.get('/products', function (req, res) {
1313
ProductsModel.find(function(err, products){//인자는 에러와 products
14-
res.render('admin/products',
14+
res.render('admin/products',//views의 위치
1515
{ products : products}//두번째 products가 위의 인자
1616
//DB에서 받은 products를 products변수명으로 내보냄
1717
);

views/admin/products.ejs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99
</tr>
1010
<% products.forEach( function(product){ %>
1111
<tr>
12-
<td><%=product.name %></td>
12+
<td><%=product.name%></td>
1313
<td>
14-
<%=product.created_at%>
14+
<%=product.getDate.year%>
15+
<%=product.getDate.month%>
16+
<%=product.getDate.day%>
1517
</td>
1618
<td>
1719
<%=product.price%>

0 commit comments

Comments
 (0)