2020年7月25日土曜日

node.jp + express + mongoDB 作業メモ

  1. インストールしたPATH
    /var/www/node/express_mongodb

  2. 起動コマンド
    npx nodemon app.js

  3. app.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const userRouter = require('./routes/user');

app.use('/user', userRouter);
//app.use(express.json());

const port = 3000;

const options = {
    useUnifiedTopology : true,
    useNewUrlParser : true
}

mongoose.connect('mongodb://127.0.0.1/test_db',options);

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => console.log('Database connection successful'));
app.get('/', (req, res) =>
    res.sendFile('/var/www/node/express_mongodb/test.html'))

app.listen(port,
    () => console.log(`Example app listening on port ${port}!`));
 
  1. models/User.js
    const mongoose = require('mongoose');

    const UserSchema = mongoose.Schema({
      name: String,
      age: Number
    });

    module.exports = mongoose.model('User',UserSchema);
     
  2. routes/user.js
    const express = require('express');

    const router = express.Router();
    const User = require('../models/User');

    router.use(express.json());
    router.use(express.urlencoded({ extended: false }));

    router.get('/', async (req, res) => {
        const users = await User.find({});
        res.json(users);
    });

    router.get('/:userID',(req, res)=>{
        User.findById(req.params.userID,(err,user)=>{
            if (err) console.log('error');
            res.send(user);
        });
    });

    router.post('/', async (req,res)=>{
        console.log(req.body);

        const user = new User({
            name: req.body.name,
            age: req.body.age
        });

        const savedUser = await user.save();
        res.json(savedUser);

    });

    router.delete('/:userID',async (req,res)=>{
        const user = await User.remove({_id: req.params.userID});
        res.send(user);
    });

    router.patch('/:userID',async (req,res)=>{
        console.log(req.body.age);
        const user = await User.updateOne({_id: req.params.userID},{$set:{age:re
    q.body.age}});
        res.send(user);
    });

    module.exports = router;

  3. test.html
    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>入力フォーム</title>
    </head>
    <body>
    <h1>入力フォーム</h1>
    <form action="/user" method="POST">
        name <input type="text" name="name"><br>
        age <input type="text" name="age"><br>
        <button type="submit">送信</button>
    </form>
    </body>
    </html>

  4. 確認方法
  • http://server:3000/
    POSTする入力フォームが表示される
  • http://server:3000/user
    GETで登録一覧がJSON形式で出力される
以上、作業途中メモ。

0 件のコメント:

コメントを投稿