駆け出しのエンジニア日記

プログラミング言語勉強中の奮闘日記

ExpressでMongooseを使う part4

農産物の商品管理アプリの作成の続きです。

今回は、商品の新規登録を表示できるようにしていきます。

フォームが必要なのと、フォームがリクエストを投げる先の二つのルーティングが必要

になります。

早速追加していきましょう。(_の部分)

・index.js

const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
const Product = require('./models/product');
mongoose.connect('mongodb://localhost:27017/farmStand',
{ useNewUrlParser: true, useUnifiedTopology: true })
.then*1;
app.set('view engine', 'ejs');
//フォームからデータを受け取れるようにする
app.use(express.urlencoded({ extended: true }));
//カテゴリを配列にしておき、ejsの方でループさせることで管理
const categories = ['果物', '野菜', '乳製品'];
 
app.get('/products', async (req, res) => {
const products = await Product.find({})
res.render('products/index', { products });
})

//商品登録フォーム
app.get('/products/new', (req, res) => {
res.render('products/new', { categories });
})

//リクエス送信先
app.post('/products', async (req, res) => {
const newProduct = new Product(req.body);
await newProduct.save();
res.redirect(`/products/${newProduct._id}`);
})
 
app.get('/products/:id', async (req, res) => {
const { id } = req.params;
const product = await Product.findById(id).populate('farm', 'name');
res.render('products/show', { product });
})
app.listen(3000, () => {
console.log('ポート3000で待機');
})

リクエストを投げた際に取得できるものが「商品名・値段・カテゴリー」です。

分割代入で必要なものだけ取得する記述でもいいのですが、今回は「req.body」で全部

取得するようにします。

(※本来はバリデーションなど入れてチェックが必要ですが、最低限のコードでシンプルにしています。)

 

そしてnew.ejsという新規のテンプレートも作成します。

・new.ejs

<!DOCTYPE html>
<html lang="ja">
<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>商品の新規登録</title>
</head>
<body>
<h2>商品の新規登録</h2>
<form action="/products" method="POST">
<label for="name">商品名</label>
<input type="text" name="name" id="name" placeholder="商品名">
<label for="price">価格</label>
<input type="number" name="price" id="price" placeholder="価格">
<label for="category">カテゴリ</label>
<select name="category" id="category">
<% for(let category of categories) {%>
<option value="<%= category %>">
<%= category %>
</option>
<% } %>
</select>
<button>登録</button>
</form>
</body>
</html>

フォームの完成したので、実際に商品を新規登録してみます。

問題なく登録できています。

*1:) => {

console.log('MongoDBコネクションOK!!');
})
.catch(err => {
console.log('MongoDBコネクションエラー!!!');
console.log(err);
});
app.set('views', path.join(__dirname, 'views'