๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

 

MongoDB์˜ ๊ตฌ์กฐ

์Šคํ‚ค๋งˆ(๊ตฌ์กฐ์  ๊ฐœ๋…, ๋ฐ์ดํ„ฐ ํ˜•ํƒœ ๋งŒ๋“ค๊ธฐ)

: Mongoose์—๊ฒŒ ๋ฐ์ดํ„ฐ(=๋‹คํ๋จผํŠธ)๋ฅผ ์–ด๋–ค ๊ตฌ์กฐ๋กœ ์ €์žฅํ•ด์•ผํ• ์ง€ ์•Œ๋ ค์ฃผ๋Š” ๊ฐ์ฒด์ด๋‹ค.

 

๋ชจ๋ธ(= document name)

: ์‹ค์ œ ๋ฐ์ดํ„ฐ๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ์Šคํ‚ค๋งˆ๋กœ ๊ตฌ์กฐ์  ์„ค๊ณ„๋ฅผ ํ•˜๊ณ  ๋ชจ๋ธ์„ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 

์ปฌ๋ ‰์…˜(์ถ”์ƒ์  ๊ฐœ๋…)

: Document(๋ฐ์ดํ„ฐ)๊ฐ€ 1๊ฐœ์ด์ƒ ๋ชจ์—ฌ ์ด๋ฃจ์–ด์ง€๋Š” ๊ฒƒ์ด Collection์ด๋‹ค.

์ปฌ๋ ‰์…˜์€ ๋ณ„๋„์˜ ์Šคํ‚ค๋งˆ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, ๋ชจ๋“  ํ•„๋“œ๊ฐ€ required=true๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์ปฌ๋ ‰์…˜ ์•ˆ์— ์žˆ๋Š” Document๋Š” ๋ชจ๋‘ ๋‹ค๋ฅธ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค. Collection์€ ์—ฌ๋Ÿฌ๊ฐœ ๋งŒ๋“ค์–ด์„œ ์„ฑ๊ฒฉ์— ๋งž๋Š” ๋ฐ์ดํ„ฐ๋“ค์˜ ๋ฌธ์„œ๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด ํšจ์œจ์ ์ด๋‹ค.

 

modelsํด๋”

models ํด๋”์— ์Šคํ‚ค๋งˆ ๋ณ„๋กœ js ํŒŒ์ผ๋“ค๋กœ ๋งŒ๋“ ๋‹ค.

 

 

//Video.js

import mongoose from "mongoose";

const VideoSchema = new mongoose.Schema({
//๋ชฝ๊ตฌ์Šค ๋ผ์ด๋ธŒ๋Ÿฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ์Šคํ‚ค๋งˆ ์ •์˜

  fileUrl: {
    type: String,
    required: "File URL is required",
    // DB์—๋Š” ๋งํฌ๋ฅผ ์ง‘์–ด๋„ฃ๊ณ , ์†Œ์Šค(์›๋ณธ)ํŒŒ์ผ์€ AWS์— ๋„ฃ์„ ์˜ˆ์ •
  },
  title: {
    type: String,
    required: "Title is required",
  },
  description: String,
  views: {
    type: Number,
    default: 0,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Comment",
        
        // Comment๋ชจ๋ธ์˜ ID๋ฅผ ํƒ€์ž…์œผ๋กœ ์ง€์ •
        // ํ•œ ๊ฐœ์˜ ๋น„๋””์˜ค ๋‹คํ๋จผํŠธ์— Comment ์Šคํ‚ค๋งˆ๋กœ ๋งŒ๋“ค์–ด์ง„ ๋‹คํ๋จผํŠธ์˜ ์•„์ด๋””๊ฐ€ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ๋จ
    },
  ],
});
 // ์Šคํ‚ค๋งˆ ์ƒ์„ฑ
//comment.js

import mongoose from "mongoose";

const CommentSchema = new mongoose.Schema({
  text: {
    type: String,
    required: "Text is required",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});
//user.js

import mongoose from "mongoose";
import passportLocalMongoose from "passport-local-mongoose";

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  avatarUrl: String, //fileUrl ๊ฐ™์€ ๊ฒƒ, ํŽ˜์ด์Šค๋ถ ํ”„๋กœํ•„์‚ฌ์ง„
  facebookId: Number,
  githubId: Number,
});

UserSchema.plugin(passportLocalMongoose, { usernameField: "email" });

์Šคํ‚ค๋งˆ ์ด๋ฆ„์˜ ์ฒซ ์ŠคํŽ ๋ง์€ ๋Œ€๋ฌธ์ž๋กœ ์ž‘์„ฑํ•œ๋‹ค.

 

const model = mongoose.model("Video", VideoSchema);
// 'VideoSchema'์Šคํ‚ค๋งˆ๋กœ 'model'๋ชจ๋ธ ๋งŒ๋“ค๊ธฐ 

export default model;
// ๋ชจ๋ธ์„ exportํ•˜๊ธฐ

 

init.jsํŒŒ์ผ

import "./models/Video";
import "./models/Comment";
import "./models/User";

Load the models before using mongoDB

๋ฐ˜์‘ํ˜•