[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 몽고DB 연동 후 데이터 전송하기 (입출금 내역 POST, GET, PATCH, DELETE 요청)

2024. 1. 28. 00:24·웹 프로젝트/👨‍👨‍👧‍👧소셜 가계부
반응형

🚧 사전 작업

필요한 패키지 설치

npm install dotenv mongoose
  • dotenv:
    • 환경변수 .env를 관리해 주는 패키지
    • computer-science-student.tistory.com 
  • mongoose:
    • 비동기 환경에서 작동하도록 설계된 MongoDB 객체 모델링 도구
    • https://velog.io/@soshin_dev/Node.js-Mongoose-%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%B4%EB%B3%B4%EC%9E%90

 

MongoDB 드라이버 설치

npm install --save mongodb

 

데이터베이스와 상호작용할 수 있는 sdk 설치

 

 

MongoDB 아틀라스 접속 및 회원가입, 데이터 베이스 만들기

 

MongoDB 연결하기(1)

회원가입 로그인 부분은 생략 하였습니다.Whitelist IP 란 승인 된 컴퓨터 IP주소를 나열하여 현재 사용하는 컴퓨터와 상호 작용 할 수 있도록 필터링 하는 IP 입니다.Database Access 메뉴에 들어와 사용

velog.io

 

MongoDB Atlas 사용법 | 코드잇

MongoDB Atlas에 가입하고 데이터베이스 주소를 사용하는 방법에 대해 알아봅시다. | MongoDB Atlas를 사용하려면 가장 먼저 가입을 해야 합니다. [Atlas 회원 가입 페이지](https://www.mongodb.com/atlas/database)

www.codeit.kr

 

 

Mongoose 이용해 DB-백엔드 연동

app.js

require("dotenv").config();

const express = require("express");
...
const bodyParser = require("body-parser");
const { default: mongoose } = require("mongoose");

app.use(bodyParser.json());

app.use("/api/transactions", transactionsRouter);

...

mongoose
  .connect(process.env.MONGO_URI)
  .then(() => {
    //db 연결이 성공할 경우 서버 연결
    app.listen(5000);
  })
  .catch((err) => {
    console.log(err);
  });

 

 

Transaction 스키마 생성

models > transaction.js

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const TransactionSchema = new Schema({
  uid: { type: String, required: true },
  date: { type: Number, required: true },
  category: { type: String, required: true },
  title: { type: String, required: true },
  amount: { type: Number, required: true },
  memo: { type: String },
});

module.exports = mongoose.model("Transaction", TransactionSchema);

데이터베이스에 저장될 데이터를 정의하는 스키마를 생성한다. 

 

 

express-validator 설치

express 유효성 검증 모듈

npm install express-validator

 

 

+) models 폴더 > http-error.js 자체 에러 처리 모델 생성

class HttpError extends Error {
  constructor(message, errorCode) {
    super(message); //'message' 프로퍼티 추가
    this.code = errorCode; //'code' 프로퍼티 추가
  }
}

module.exports = HttpError;

 

 

🚧 백엔드 → DB  POST 요청 보내기

transactions-controller.js

const { v4: uuid } = require("uuid");
const { validationResult } = require("express-validator");

const HttpError = require("../models/http-error");
const Transaction = require("../models/transaction");

...

const createTransaction = async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(HttpError(errors.array(), 422));
  }
  const { uid, category, title, amount, memo } = req.body;

  //모델 생성 완료
  const createdTransaction = new Transaction({
    uid,
    date: new Date().getTime(),
    category,
    title,
    amount,
    memo,
  });

  try {
    await createdTransaction.save();
  } catch (e) {
    const error = new HttpError("입출금 내역 저장 실패", 500);
    return next(error);
  }

  res.status(201).json({ transaction: createdTransaction });
};
...

포스트맨으로 post 요청을 보낸다
실제 db에 post 요청된 데이터가 저장되어 있는 모습

 

 

🚧 백엔드 → DB  GET 요청 보내기

transactions-controller.js > getTransactionById

const getTransactionById = async (req, res, next) => {
  const transactionId = req.params.tid; // type: string

  let transaction;
  try {
    transaction = await Transaction.findById(transactionId);
  } catch (e) {
    //GET 요청에 문제가 생겼을 때
    const error = new HttpError("입출금내역을 불러오지 못했습니다.", 500);
    return next(error);
  }

  // GET 요청에 문제가 없지만 입출금내역을 찾을 수 없는 경우 에러 핸들링
  if (!transaction) {
    const error = new HttpError(
      "해당 ID에 대한 입출금내역을 찾지 못했습니다.",
      404
    );
    return next(error);
  }

  res.json({ transaction: transaction.toObject({ getters: true }) });
};

mongoose 함수 findById를 이용해 params의 id와 일치하는 Transaction 스키마의 데이터를 찾아온다. 

GET 요청이 성공적으로 완료된 모습

 

transactions-controller.js > getTransactionsByUserId

const getTransactionsByUserId = async (req, res, next) => {
  const userId = req.params.uid;

  let transactions;
  try {
    transactions = await Transaction.find({ uid: userId });
  } catch (e) {
    const error = new HttpError("입출금내역을 불러오지 못했습니다.", 500);
    return next(error);
  }

  if (!transactions || transactions.length === 0) {
    return next(
      new HttpError("해당 유저의 입출금내역을 찾지 못했습니다.", 404)
    );
  }

  res.json({
    transactions: transactions.map((t) => t.toObject({ getters: true })),
  });
};

mongoose 함수 find를 이용해 params의 id와 일치하는 Transaction 스키마의 데이터를 모두 찾아온다.

데이터가 여러 건이기 때문에, 요청 전송 현황 확인을 위해 데이터를 불러올 때 map 함수를 사용했다.  

GET 요청이 성공적으로 완료된 모습
오류가 생겼을 때의 화면 (id를 틀리게 입력함)

 

 

🚧 백엔드 → DB  PATCH 요청 보내기

transactions-controller.js

const updateTransaction = async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(HttpError(errors.array(), 422));
  }

  const { date, category, title, amount, memo } = req.body;
  const transactionId = req.params.tid;

  //id로 해당 입출금 내역 불러오기
  let transaction;
  try {
    transaction = await Transaction.findById(transactionId);
  } catch (e) {
    const error = new HttpError("입출금내역을 불러오지 못했습니다.", 500);
    return next(error);
  }

  //내용 업데이트
  transaction.date = date;
  transaction.category = category;
  transaction.title = title;
  transaction.amount = amount;
  transaction.memo = memo;

  try {
    await transaction.save();
  } catch (e) {
    const error = new HttpError("입출금 내역 수정 실패", 500);
    return next(error);
  }

  res
    .status(200)
    .json({ transaction: transaction.toObject({ getters: true }) });
};

findById 함수로 우선 입출금 내역을 불러오고, 내용 업데이트 후 데이터베이스에 수정된 내용을 save 함수로 저장하는 두 단계를 거친다.

 

 

🚧 백엔드 → DB  DELETE 요청 보내기

transactions-controller.js

const deleteTransaction = async (req, res, next) => {
  const transactionId = req.params.tid;

  let transaction;
  try {
    transaction = await Transaction.findById(transactionId);
  } catch (e) {
    const error = new HttpError("입출금내역을 불러오지 못했습니다.", 500);
    return next(error);
  }

  try {
    await transaction.deleteOne({ id: transactionId });
  } catch (e) {
    const error = new HttpError("입출금내역을 삭제하지 못했습니다.", 500);
    return next(error);
  }

  res.status(200).json({ message: "삭제 완료", transactionId });
};

findById 함수로 id에 해당하는 입출금 내역을 불러오고, 해당 데이터를 deleteOne 함수를 이용해 삭제했다. 

삭제완료 메시지가 정상적으로 확인된다.

 

 

 


참고

 

mongoose 함수

 

[ Node.js ] Mongoose 를 사용해보자!

Mongoose 모듈은 MongoDB 라는 NoSQL 데이터베이스를 Node.js로 사용할 수 있도록 하는 확장 모듈 중 하나 입니다.Mongoose는 데이터를 만들고 관리하기 위해 스키마 \[ Schema ]를 만들고, 그 스키마로 모델을

velog.io

 

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'웹 프로젝트 > 👨‍👨‍👧‍👧소셜 가계부' 카테고리의 다른 글

[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: JavaScript → TypeScript 마이그레이션 1(세팅, App, AppRouter)  (0) 2024.03.27
[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 배포 (서버: Koyeb, 프론트: vercel)  (0) 2024.03.07
[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 리덕스(Redux)로 가계부 데이터 상태 관리 1(리덕스 선택이유, 리덕스 정의 및 스토어, 액션, 리듀서 정의, 덕스패턴 적용까지)  (0) 2024.03.07
[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 백엔드 구현하기 (입출금 내역 - POST, PATCH, DELETE 요청)  (0) 2024.01.27
[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 백엔드 구현하기 (입출금 내역 - GET 요청 보내기)  (0) 2024.01.26
[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 백엔드 구현하기 (사전 작업 - express, nodemon, body-parser 설치 및 테스트 작성)  (1) 2024.01.25
'웹 프로젝트/👨‍👨‍👧‍👧소셜 가계부' 카테고리의 다른 글
  • [React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 배포 (서버: Koyeb, 프론트: vercel)
  • [React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 리덕스(Redux)로 가계부 데이터 상태 관리 1(리덕스 선택이유, 리덕스 정의 및 스토어, 액션, 리듀서 정의, 덕스패턴 적용까지)
  • [React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 백엔드 구현하기 (입출금 내역 - POST, PATCH, DELETE 요청)
  • [React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 백엔드 구현하기 (입출금 내역 - GET 요청 보내기)
청량리 물냉면
청량리 물냉면
프로그래밍 공부를 하고 있습니다. 공부 내용 정리 겸 정보 공유를 목적으로 합니다.
    반응형
  • 청량리 물냉면
    노력중인 블로그
    청량리 물냉면
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 프로그래밍
        • Programming
        • C | C++
        • Java
        • Python
      • 웹 프로그래밍
        • HTML | CSS
        • JavaScript | TypeScript
        • React
        • Vue.js
        • Next.js
        • Spring & Spring Boot
        • JSP & Servlet
        • DB
      • 웹 프로젝트
        • 웹 프로젝트
        • 🥨스낵몰
        • 👨‍👨‍👧‍👧소셜 가계부
        • 🌜꿈 일기장
        • 🔮포트폴리오 사이트
        • 🏃‍♂️팀 프로젝트: 일정관리 프로그램
        • 📈팀 프로젝트: AI기반 주식 분석 플랫폼
        • 😺Just Meow It: 고양이의 조언
      • 앱 프로그래밍
        • Flutter
        • Kotlin
      • Problem Solving
        • 백준
        • 프로그래머스
        • SWEA
      • Computer Science
        • 알고리즘
        • 컴퓨터 네트워크
        • 이산수학
      • Developer
        • 후기
        • 자료정리
        • 취업 | 취준
        • 웹개발 교육 프로그램
        • TIL
  • 블로그 메뉴

    • 홈
    • Github
  • 공지사항

    • 프로그래밍 공부 중😊
  • 인기 글

  • 태그

    React
    SWEA
    백준
    Next.js
    파이썬
    리액트
    강의내용정리
    프로그래머스
    포트폴리오
    spring boot
    bfs
    자바스크립트
    타입스크립트
    블로그 제작
    자바
    구현
    알고리즘
    mysql
    공식문서
    ZeroCho
    d3
    컴퓨터네트워크
    웹사이트
    AWS
    Jiraynor Programming
    플러터
    프로젝트
    뉴렉처
    클론 프로젝트
    Til
  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
청량리 물냉면
[React/Node.js/Express/MongoDB] 소셜 가계부 프로젝트 구현 일지: 몽고DB 연동 후 데이터 전송하기 (입출금 내역 POST, GET, PATCH, DELETE 요청)
상단으로

티스토리툴바