farm 스키마와 Product 스키마 상호 연결
const Farm = require('./models/farm');
Farm 에 새로운 product 추가하기
-> /farms/:farm_id/prodcuts/new 의 형태
여기서 제출을 누르게 되면
/farms/:farm_id/prodcuts/ 로 POST 됨.\
//Farm Routes
//농장들 목록들 페이지
app.get('/farms', async(req,res)=> {
const farms = await Farm.find({})
res.render('farms/index', { farms })
})
//새로운 farm 추가하는 from 창 (Add a Farm Form)
app.get('/farms/new', (req,res)=> {
res.render('farms/new')
})
// farm 에 대한 정보 (이름,가격, 판매중인 품목들)
app.get('/farms/:id', async(req,res)=> {
const { id } = req.params;
const farm = await Farm.findById(id).populate('products')
res.render('farms/show' , { farm })
})
// 새로운 farm 추가시 index에 추가시키기.
app.post('/farms', async(req,res)=> {
const farm = new Farm(req.body);
await farm.save();
res.redirect('farms/')
})
//해당 농장에 새로운 품목 추가시키기
app.get('/farms/:id/products/new', async (req,res)=> {
const { id } = req.params;
const farm = await Farm.findById(id);
res.render('products/new' , { categories, farm })
})
// 새로운 농장에 추가된 품목 보기
app.post('/farms/:id/products', async(req,res)=> {
const { id } = req.params;
const farm = await Farm.findById(id);
const { name, price, category } = req.body;
const product = new Product({ name, price, category});
farm.products.push(product);
product.farm = farm;
await farm.save();
await product.save();
res.redirect(`/fa
farms 폴더 내
<show.ejs>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%= product.name %></title>
</head>
<body>
<h1><%=product.name %></h1>
<ul>
<li>Price: $ <%= product.price %></li>
<li>
Category:<a href="/products?category=<%= product.category %>"
><%= product.category %></a
>
</li>
<li>
Farm: <a href="/farms/<%=product.farm._id%>"><%=product.farm.name%></a>
</li>
</ul>
<a href="/products">All Products</a>
<a href="/products/<%=product._id%>/edit">Edit Product</a><br />
<br />
<form action="/products/<%=product._id%>?_method=DELETE" method="POST">
<button>Delete</button>
</form>
</body>
</html>
prodcuts 폴더 내
<new.ejs>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>New Product</title>
</head>
<body>
<h1><%=farm.name%></h1>
<h2>Add a Product</h2>
<form action="/farms/<%=farm._id%>/products" method="POST">
<label for="name">Product Name</label>
<input type="text" name="name" id="name" placeholder="product name" />
<label for="price">Price (Unit)</label>
<input type="number" id="price" name="price" placeholder="price" />
<label for="category">Select Category</label>
<select name="category" id="category">
<% for(let category of categories){ %>
<option value="<%=category%>"><%=category%></option>
<% }%>
</select>
<button>Submit</button>
</form>
<a href="/farms/<%=farm._id%>">Back to Farm</a>
</body>
</html>
farm 삭제시 해당 농장에 포함된 product 들도 삭제 하기.