Node.js, Express.js, MongoDB를 사용한 CRUD 예제

67923 단어 crudexpressnodemongodb
이번 포스팅에서는 Node.js와 MongoDB를 이용한 기본 CRUD 동작에 대해 알아보겠습니다.
CRUD는 모든 웹 애플리케이션의 기본 개념입니다.

이 CRUD 애플리케이션에서는 태스크 모델을 사용하여 할 일 애플리케이션에 대한 태스크를 생성합니다.
여기서 작업 모델에는 다음이 포함됩니다.
  • 아이디
  • 제목
  • 설명
  • 생성 시간
  • 업데이트 시간

  • 이제 작업에 대한 모델을 생성합니다...

    const { Schema, model } = require('mongoose')
    
    const taskSchema = new Schema({
        title: {
            type: String
        },
        description: {
            type: String
        }
    }, {
        timestamps: true
    })
    
    const Task = model('Task', taskSchema)
    module.exports = Task
    


    이제 서버를 생성하고 서버를 데이터베이스에 연결합니다.

    require('dotenv').config()
    
    const express = require('express')
    const mongoose = require('mongoose')
    const http = require('http')
    
    const setMiddlewares = require('./middleware/middlewares')
    const setRoutes = require('./router/routes')
    
    
    
    const app = express()
    const server = http.createServer(app)
    
    setMiddlewares(app)
    setRoutes(app)
    
    
    const PORT = process.env.PORT || 1000
    const DB_USER = process.env.DB_USER
    const DB_PASSWORD = process.env.DB_PASSWORD
    const DB_NAME = process.env.DB_NAME
    
    
    
    mongoose.connect(`mongodb+srv://DB_USER :DB_PASSWORD [email protected]/DB_NAME?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true })
        .then(() => {
            console.log('Database connect success')
            server.listen(PORT, () => {
                console.log('Server Is Ready')
            })
        }).catch(e => {
            return console.log(e)
        })
    


    이제 태스크 생성, 태스크 읽기, 태스크 업데이트 및 태스크 삭제를 위한 컨트롤러를 생성합니다.

    작업 컨트롤러 만들기:

    exports.createTaskController = async(req, res, next) => {
        try {
            let { title, description } = req.body
            let newTask = new Task({
                title,
                description
            })
    
            await newTask.save(newTask)
                .then(data => {
                    return res.send(data)
                }).catch(err => {
                    res.status(500).send({
                        msg: 'task create fail'
                    })
                })
    
            console.log(newTask)
        } catch (e) {
            console.log(e)
            next()
        }
    }
    


    모든 태스크 컨트롤러 읽기:

    exports.getTaskController = async(req, res, next) => {
        try {
            await Task.find()
                .then(tasks => {
                    return res.send(tasks)
                }).catch(err => {
                    res.status(500).send({
                        msg: 'no tast found'
                    })
                })
    
        } catch (e) {
            console.log(e)
            next()
        }
    }
    


    단일 작업 컨트롤러 읽기:

    exports.getSingleTask = async(req, res, next) => {
        try {
            let taskId = req.params.id
            await Task.findById(taskId)
                .then(task => {
                    if (task) {
                        return res.send(task)
                    } else {
                        return res.send({ msg: 'no task found' })
                    }
    
                }).catch(err => {
                    res.status(500).send({
                        msg: 'no task found'
                    })
                })
    
        } catch (e) {
            console.log(e)
            next()
        }
    }
    


    작업 컨트롤러 업데이트:

    exports.updateTastController = async(req, res, next) => {
        try {
            let taskId = req.params.id
            let { title, description } = req.body
            let task = await Task.findById(taskId)
            console.log(task)
            if (!task) {
                return res.json({ msg: 'no task found' })
            }
    
            await Task.findByIdAndUpdate(taskId, {
                $set: {
                    title,
                    description
                }
            }, { new: true }).then(data => {
                return res.send(data)
            }).catch(err => {
                res.status(500).send({
                    msg: 'task update fail'
                })
            })
    
        } catch (e) {
            console.log(e)
            next()
        }
    }
    


    태스크 컨트롤러 삭제:

    exports.deleteTaskController = async(req, res, next) => {
        try {
            let taskId = req.params.id
            await Task.findByIdAndDelete(taskId)
                .then(data => {
                    return res.send(data)
                }).catch(err => {
                    res.status(500).send({
                        msg: 'task delete fail'
                    })
                })
        } catch (e) {
            console.log(e)
        }
    }
    


    이제 모든 작업에 대한 경로를 만듭니다.
    route.js:

    const crudRoute = require('../router/cruduRoute')
    
    const routes = [{
            path: '/tasks',
            handler: crudRoute
        },
        {
            path: '/',
            handler: (req, res, next) => {
                return res.json({ msg: 'Welcome to my application' })
            }
        }
    ]
    
    module.exports = (app) => {
        routes.forEach(r => {
            if (r.path == '/') {
                app.get(r.path, r.handler);
            } else {
                app.use(r.path, r.handler)
            }
        })
    }
    


    crudRoute.js:

    const router = require('express').Router()
    const { getTaskController, getSingleTask, createTaskController, updateTastController, deleteTaskController } = require('../controller/crudController')
    
    
    router.get('/', getTaskController)
    router.get('/:id', getSingleTask)
    router.post('/create', createTaskController)
    router.put('/update/:id', updateTastController)
    router.delete('/delete/:id', deleteTaskController)
    
    module.exports = router
    


    이제 프로젝트를 실행하고 모든 출력을 얻을 수 있습니다.
    작업 만들기:
    API: http://localhost:1000/tasks/createJSON 데이터:


    모든 작업 가져오기
    API: http://localhost:1000/tasks/
    [
      {
        "_id": "62eaa8fff44996bbc06820ba",
        "title": "this is title",
        "description": "this is the description",
        "createdAt": "2022-08-03T16:57:35.029Z",
        "updatedAt": "2022-08-03T16:57:35.029Z",
        "__v": 0
      },
      {
        "_id": "62eaa90af44996bbc06820bc",
        "title": "this is title",
        "description": "this is the description",
        "createdAt": "2022-08-03T16:57:46.439Z",
        "updatedAt": "2022-08-03T16:57:46.439Z",
        "__v": 0
      },
      {
        "_id": "62eaa90bf44996bbc06820c0",
        "title": "this is title",
        "description": "this is the description",
        "createdAt": "2022-08-03T16:57:47.883Z",
        "updatedAt": "2022-08-03T16:57:47.883Z",
        "__v": 0
      },
      {
        "_id": "62eaa90cf44996bbc06820c2",
        "title": "this is title",
        "description": "this is the description",
        "createdAt": "2022-08-03T16:57:48.794Z",
        "updatedAt": "2022-08-03T16:57:48.794Z",
        "__v": 0
      },
      {
        "_id": "62eab011dc6db60de9a247c0",
        "title": "this is title",
        "description": "this is the description",
        "createdAt": "2022-08-03T17:27:45.876Z",
        "updatedAt": "2022-08-03T17:27:45.876Z",
        "__v": 0
      }
    ]
    
    


    단일 작업 가져오기
    API: http://localhost:1000/tasks/62eaa8fff44996bbc06820ba

    작업 업데이트
    API: http://localhost:1000/tasks/update/62eaa8fff44996bbc06820ba

    작업 삭제
    API: http://localhost:1000/tasks/delete/62eaa8fff44996bbc06820ba
    전체 코드:
    app.js

    require('dotenv').config()
    
    const express = require('express')
    const mongoose = require('mongoose')
    const http = require('http')
    
    const setMiddlewares = require('./middleware/middlewares')
    const setRoutes = require('./router/routes')
    
    
    
    const app = express()
    const server = http.createServer(app)
    
    setMiddlewares(app)
    setRoutes(app)
    
    
    const PORT = process.env.PORT || 1000
    const DB_USER = process.env.DB_USER
    const DB_PASSWORD = process.env.DB_PASSWORD
    const DB_NAME = process.env.DB_NAME
    
    
    
    mongoose.connect(`mongodb+srv://DB_USER :DB_PASSWORD @mycluster.oazue.mongodb.net/DB_NAME ?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true })
        .then(() => {
            console.log('Database connect success')
            server.listen(PORT, () => {
                console.log('Server Is Ready')
            })
        }).catch(e => {
            return console.log(e)
        })
    


    미들웨어.js

    const express = require('express')
    const morgan = require('morgan')
    
    
    const middlewares = [
        morgan('dev'),
        express.urlencoded({ extended: true }),
        express.json()
    ]
    
    module.exports = (app) => {
        middlewares.forEach(m => {
            app.use(m)
        })
    }
    


    Task.js

    const { Schema, model } = require('mongoose')
    
    const taskSchema = new Schema({
        title: {
            type: String
        },
        description: {
            type: String
        }
    }, {
        timestamps: true
    })
    
    const Task = model('Task', taskSchema)
    module.exports = Task
    


    crudController.js

    const Task = require('../model/Task')
    
    
    // get all tasks
    exports.getTaskController = async(req, res, next) => {
        try {
            await Task.find()
                .then(tasks => {
                    return res.send(tasks)
                }).catch(err => {
                    res.status(500).send({
                        msg: 'no tast found'
                    })
                })
    
        } catch (e) {
            console.log(e)
            next()
        }
    }
    
    // get single task
    
    exports.getSingleTask = async(req, res, next) => {
        try {
            let taskId = req.params.id
            await Task.findById(taskId)
                .then(task => {
                    if (task) {
                        return res.send(task)
                    } else {
                        return res.send({ msg: 'no task found' })
                    }
    
                }).catch(err => {
                    res.status(500).send({
                        msg: 'no task found'
                    })
                })
    
        } catch (e) {
            console.log(e)
            next()
        }
    }
    
    
    // create task
    exports.createTaskController = async(req, res, next) => {
        try {
            let { title, description } = req.body
            let newTask = new Task({
                title,
                description
            })
    
            await newTask.save(newTask)
                .then(data => {
                    return res.send(data)
                }).catch(err => {
                    res.status(500).send({
                        msg: 'task create fail'
                    })
                })
    
            console.log(newTask)
        } catch (e) {
            console.log(e)
            next()
        }
    }
    
    //update task 
    
    exports.updateTastController = async(req, res, next) => {
        try {
            let taskId = req.params.id
            let { title, description } = req.body
            let task = await Task.findById(taskId)
            console.log(task)
            if (!task) {
                return res.json({ msg: 'no task found' })
            }
    
            await Task.findByIdAndUpdate(taskId, {
                $set: {
                    title,
                    description
                }
            }, { new: true }).then(data => {
                return res.send(data)
            }).catch(err => {
                res.status(500).send({
                    msg: 'task update fail'
                })
            })
    
        } catch (e) {
            console.log(e)
            next()
        }
    }
    
    // delete task 
    
    exports.deleteTaskController = async(req, res, next) => {
        try {
            let taskId = req.params.id
            await Task.findByIdAndDelete(taskId)
                .then(data => {
                    return res.send(data)
                }).catch(err => {
                    res.status(500).send({
                        msg: 'task delete fail'
                    })
                })
        } catch (e) {
            console.log(e)
        }
    }
    


    route.js

    const crudRoute = require('../router/cruduRoute')
    
    const routes = [{
            path: '/tasks',
            handler: crudRoute
        },
        {
            path: '/',
            handler: (req, res, next) => {
                return res.json({ msg: 'Welcome to my application' })
            }
        }
    ]
    
    module.exports = (app) => {
        routes.forEach(r => {
            if (r.path == '/') {
                app.get(r.path, r.handler);
            } else {
                app.use(r.path, r.handler)
            }
        })
    }
    


    crudRoute.js

    const router = require('express').Router()
    const { getTaskController, getSingleTask, createTaskController, updateTastController, deleteTaskController } = require('../controller/crudController')
    
    
    router.get('/', getTaskController)
    router.get('/:id', getSingleTask)
    router.post('/create', createTaskController)
    router.put('/update/:id', updateTastController)
    router.delete('/delete/:id', deleteTaskController)
    
    module.exports = router
    


    패키지.json

    {
        "name": "backend",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1",
            "start": "nodemon app.js"
        },
        "keywords": [],
        "author": "",
        "license": "ISC",
        "dependencies": {
            "dotenv": "^16.0.1",
            "express": "^4.18.1",
            "express-validator": "^6.14.2",
            "moment": "^2.29.4",
            "mongoose": "^6.5.0",
            "morgan": "^1.10.0",
            "multer": "^1.4.5-lts.1",
            "nodemon": "^2.0.19"
        }
    }
    


    파일

    좋은 웹페이지 즐겨찾기