Backend 백엔드

[ 28 ] mongoose 로 Board_API 만들기 실습

박민우_ 2024. 8. 20. 22:10

docker-compose.yaml 파일 변경시 빌드를 다시 할필요 없는 이유

docker-compose.yaml 파일은 컨테이너 간의 관계, 네트워크 , 환경 변수 등의 설정을 하는 파일이여서 도커 이미지를 만드는 빌드 과정과는 별개이다. 

모델 ( Model )

모델은 데이터의 구조와 형식을 정의하는 틀이다.

MongoDB 자체에는 ' 모델 ' 개념이 없지만 ,Mongoose 와 같은 ODM 라이브러리를 사용하면 모델을 정의해서 사용한다.

 

// ./models/board.model.js 파일

import mongoose from 'mongoose'

const boardSchema = new mongoose.Schema({
    writer : String,
    title : String,
    contents : String,
})

export const Board = mongoose.model("Board",boardSchema)

게시글 작성 API

// index.js 파일


import { Board } from './models/board.model.js'



app.post('/boards', async function(req,res){

    // 1. 브라우저에서 보내준 데이터 확인하기
    console.log(req)
    console.log("----")
    console.log(req.body)

    // 2. DB에 접속 후 , 데이터를 저장
    const board = new Board({
        writer : req.body.writer,
        title : req.body.title,
        contents : req.body.contents
    })

    await board.save()

    // 3. DB에 저장된 결과를 브라우저에 응답 ( response ) 주기
    res.send('게시물 등록에 성공하였습니다')
})

게시글 조회 API

// index.js 파일

import { Board } from './models/board.model.js'


app.get('/boards', async function(req,res){


    const result = await Board.find()

    // 2. DB에서 꺼내온 결과를 브라우저에 응답 ( response ) 주기

    res.send(result)
})
728x90