카테고리 없음

[게시판 CRUD 만들기] 2. express와 mongo db 연결하기

전호영 2023. 10. 15. 03:06

오늘의 목표

  • Mongo db와 express 연결하기
  • client에서 data를 backend로 보내기

1. Mongo db와 express 연결하기

 

[NoSQL] MongoDB란? 맥북(M1) 몽고디비, compass 설치

✅ MongoDB란? 필요한 쿼리 제공 및 인덱싱을 활용해 원하는 수준의 확장성과 유연성을 제공하는 문서 데이터베이스. NoSQL 데이터베이스 시스템이다. 문서지향 데이터베이스로JSON과 유사한 BinaryJSO

jie0025.tistory.com

(Mongo DB 로컬에 없다면 위 글을 따라 설치!)

 

Mongo db와 express를 연결하기 위해서 mongoose를 사용

npm i mongoose

 

mongo db와 express를 연결하기 위한 기본 세팅을 해보자.

 

12. MongoDB 연동 I - mongoose · node.js 서버구축하기

 

javafa.gitbooks.io

 

 

Mongoose v7.6.1: Getting Started

First be sure you have MongoDB and Node.js installed. Next install Mongoose from the command line using npm: npm install mongoose --save Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is

mongoosejs.com

(위 두 문서를 참고)

import mongoose from "mongoose";
mongoose.connect("mongodb://127.0.0.1:27017/bulletin"); // terminal에서 mongo를 실행하면 mongo db 주소를 알 수 있음.

const db = mongoose.connection;


const handleDbOpen = () => {
  console.log("✅  Conncected to DB");
};
const handleDbError = (error) => {
  console.log("❌  DB Error", error);
};

db.on("error", handleDbError); // on : 여러번 발생 가능한 이벤트
db.once("open", handleDbOpen); // once : 한번만 발생하는 이벤트

terminal을 켠 뒤 mongo 명령어를 입력해 MongoDB shell로 들어가자.

show dbs를 입력해 bulletin db가 생성되었는지 확인!

bulletin db가 생성됨을 알 수 있다!

 

2. client에서 data를 backend로 보내기

클라이언트 모습

form에서 POST로 날아오는 데이터는 req의 body에 담겨온다.

 

Express body-parser middleware

body-parser Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the req.body property. Note As req.body’s shape is based on user-controlled input, all properties and values in this object a

expressjs.com

express에서 req.body는 그냥 볼 수 없다.

body-parser를 다운로드 받은 뒤 볼 수 있다.

express@4.16.0  부터 express에 bodyparser가 내장됨.

server.js에

app.use(express.urlencoded({ extended: true }));

추가해주자.

 

브라우저에서 날아올 데이터를 받기 위해 router를 작성해주자.

app.post("/document/write", (req, res) => {
  const {
    body: { title, content },
  } = req;
  console.log(`title: ${title} , content: ${content}`);
  return res.redirect("/document/write");
});

정말 데이터가 수신되는지 확인

데이터가 잘 수신된다!

 

다음 시간엔 

  • 수신한 data를 mongo db에 저장
  • db에 저장된 글을 메인 페이지에서 보기
  • 글 읽기

를 구현해보자!

 

끝!