
์คํค๋ง(๊ตฌ์กฐ์ ๊ฐ๋ , ๋ฐ์ดํฐ ํํ ๋ง๋ค๊ธฐ)
: 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
'๐ Back > ๐ MongoDB' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| MongoDB Atlas ๋ฑ๋ก&์ฌ์ฉ (๋ฌด๋ฃ mongoDB Cloud ์๋น์ค) (0) | 2021.05.18 |
|---|---|
| mongoDB ์ฐ๊ฒฐํ๊ธฐ (0) | 2021.02.05 |
| MongoDB ๋? ๋ํ์ ์ธ NOSQL ๋ฐ์ดํฐ๋ฒ ์ด์ค (0) | 2021.01.19 |