「入門Node.jsプログラミング 」の感想・備忘録5

スポンサーリンク
「入門Node.jsプログラミング 」の感想・備忘録4の続き

Lesson15

コントローラとモデルを接続する

1. インストール

  • npm init
  • npm install express ejs express-ejs-layouts http-status-codes mongodb mongoose

2. index.jsの作成

'use strict';

const express = require('express');
const app = express();
const subscribersController = require("./controllers/subscribersController");
const layouts = require("express-ejs-layouts");
const mongoose = require("mongoose");
app.set('port', process.env.PORT || 3000);
app.set("view engine", "ejs");
app.use(layouts);
app.use(
  express.urlencoded({
    extended: false
  })
);
app.use(express.json());

mongoose.connect(
  'mongodb://localhost:27017/recipe',
  {useNewUrlParser: true}
);
const db = mongoose.connection;
db.once('open', () => {
  console.log('connected to mongodb.');
});

app.get("/subscribers", subscribersController.getAllSubscribers, (req, res, next) => {
  res.render("subscribers", { subscribers: req.data });
});

app.listen(app.get('port'), () => {
  console.log(`Server running at http://localhost:${app.get('port')}`);
});

3. controllers/subscribersController.jsの作成

"use strict";

const Subscriber = require("../models/subscriber");

exports.getAllSubscribers = (req, res, next) => {
  Subscriber.find({}, (error, subscribers) => {
    if (error) next(error);
    req.data = subscribers;
    next();
  });
};

4. models/subscriber.jsの作成

'use strict';

const mongoose = require('mongoose');
const subscriberSchema = mongoose.Schema({
  name: String,
  email: String,
  zipCode: Number
});
module.exports =  mongoose.model('Subscriber', subscriberSchema);

5. views/subscribers.ejsの作成

<% subscribers.forEach(s => { %>
  <p>Name:<%= s.name %></p>
  <p>Email:<%= s.email %></p>
<% }); %>

POSTデータをモデルに保存する

1. index.jsに追加

app.get("/contact", subscribersController.getSubscriptionPage);
app.post("/subscribe", subscribersController.saveSubscriber);

2. controllers/subscribersController.jsに追加

exports.getSubscriptionPage = (req, res) => {
  res.render("contact");
};

exports.saveSubscriber = (req, res) => {
  let newSubscriber = new Subscriber({
    name: req.body.name,
    email: req.body.email,
    zipCode: req.body.zipCode
  });
  newSubscriber.save((error, result) => {
    if (error) res.send(error);
    res.render("thanks");
  });
};

3. views/contact.ejsの作成

<form action="/subscribe" method="post">
  <p>Name : <input type="text" name="name" value=""></p>
  <p>Email : <input type="email" name="email" value=""></p>
  <p>zipCode : <input type="text" name="zipCode" value=""></p>
  <p><input class="button" type="submit" value="submit"></p>
</form>

MongooseでPromiseを使う

1. index.jsに追加

app.get("/subscribers", subscribersController.getAllSubscribers);

2. controllers/subscribersController.jsに追加

exports.getAllSubscribers = (req, res) => {
  Subscriber.find({})
    .then(subscribers => {
      res.render("subscribers", {subscribers: subscribers});
    });
};

コメント