토이프로젝트_포토앨범(2단계 mongoose로 document의 schema 생성하기)

Suding·2022년 11월 5일
0

업로드한 이미지와 텍스트를 mongodb에 저장하게 될텐데 mongodb는 schema가 없는 noSQL document 데이터베이스이기 때문에 mongoose를 사용해서 document의 structure을 잡아준다.
(database > collection > document)

1. 업로드된 파일의 데이터를 db에 저장하는 규칙 선언하기

(username, comment, image로 데이터를 string 형식으로 저장하자는 규칙이다)

   const mongoose = require('mongoose');
   const fileSchema = new mongoose.Schema({
       username: {
           type: String,
           required: true,
       },
       comment: {
           type: String,
           required: true,
       },
       image: {
           type: String,
           required: true,
       }
   });

2. 컬렉션 생성하기, schema 등록하기

module.exports = mongoose.model('Files',fileSchema);

Files 라는 컬렉션이름이 만들었다 (db 에서 보면 files 라는 컬랙션이 생성된다)

fileSchema가 등록되어 앞으로 컬렉션에 저장되는 데이터들은 schema 조건을 충족하는지 검사가 이뤄 진다.

module.exports 를 통해 model 을 호출할수 있게 되었다.

routes.js 파일에서 Files를 require 해준다. 이렇게 하면, fileSchema가 등록된가
model file이 호출 될때마다 DB 작업이 이뤄질때 schema에 맞춰 검사가 이뤄 진다.


레퍼런스:
https://www.zerocho.com/category/MongoDB/post/59a1870210b942001853e250

profile
웹개발자가 되고 싶은 수딩의 코딩 일지

0개의 댓글