[유튜브 클론코딩] 3.3 Video Model

2021. 3. 1. 16:45Projects/유튜브 클론코딩

728x90
반응형

3.3 Video Model

스키마

MongoDB에 우리의 파일들이 어떤 식으로 생겨야 할 지 알려줘야 하기 때문에 스키마를 작성한다.

→ 이런게 file의 형태, 즉 model의 형태

이것들은 models라는 폴더에 저장될 것이다.

 

MongoDB에 스키마 작성하기(models > Video.js)

models 폴더를 만들고 Video.js 파일을 만든다.

import mongoose from "mongoose";

const VideoSchema = new mongoose.Schema({

})

↑ Video.js

 

본격적으로 스키마를 정의한다.

 

import mongoose from "mongoose";

const VideoSchema = new mongoose.Schema({

    fileUrl: {

        type: String,

        required: 'File URL is required'

    },

    title : {

        type: String,

        required : "Title is required"

    },

    description : String,

    views:{

        type: Number,

        default: 0

    },

    createdAt : {

        type: Date,

        default: Date.now

    }

});
  • fileUrl
    • 우린 절대 Video를 Database에 저장하지 않을 것이다. (video의 주소를 넣는거지 video 파일자체를 넣는게 아니라는 말)
    • 왜냐하면 그렇게 하면 database가 겁나 무거워지기 때문이다.
    • fileUrl은 type은 String, required로 설정하고 required가 충족되지 못하면 에러 메시지는  'File URL is required" (fileUrl 값이 없는 Video를 생성하려 한다면 이 에러 메시지를 받을 것이다)
  • title
    • type은 String
  • description
  • views
    • type은 number
    • default를 0으로 설정해서 처음 Video가 생성되면 views를 0이 되게 한다
  • createdAt
    • type은 Date
    • default로는 Date.now를 준다. Date.now는 현재 날짜를 받는 함수이다.

 

스키마에 대해서 더 알고싶다면 mongoose documentation의 schema section에서 모든 option을 확인할 수있다

 

schema를 이용해서 model을 만들어보기

import mongoose from "mongoose";

const VideoSchema = new mongoose.Schema({

    fileUrl: {

        type: String,

        required: 'File URL is required'

    },

    title : {

        type: String,

        required : "Title is required"

    },

    description : String,

    views:{

        type: Number,

        default: 0

    },

    createdAt : {

        type: Date,

        default: Date.now

    }

});

const model = mongoose.model("Video", VideoSchema);

export default model;

↑ Video.js

이제 이 schema를 이용해서 model을 만들어보자

스키마는 definition(정의) 같은 것

 

현재 우리 Database는 이걸 생성했다는 걸 인지 못하고 있다. 연결은 되어있지만 거기에 model이 있다는 건 알지 못하므로 추가를 해줘야 한다.

 

init.js에 model을 추가하기

init.js로 가서 추가를 해준다. 여기서 model을 import한다

import "./db";

import app from "./app";

import dotenv from "dotenv";

dotenv.config();

import "./models/Video";

const PORT = process.env.PORT || 4000;

const handleListening = () => console.log(`✅Listening on: http://localhost:${PORT}`);

app.listen(PORT, handleListening);

 

728x90
반응형