Backend ๐Ÿ“š/Node.js

[Node] MongoDB Model, Schema

leejaejae 2024. 7. 30. 18:48

0. ๋“ค์–ด๊ฐ€๊ธฐ ์•ž์„œ!

  • User Model ์ƒ์„ฑ์ด๋ž€
    • ํšŒ์›๊ฐ€์ž…์„ ํ•  ๋•Œ ๋‚ด๊ฐ€ ์“ด ๋‚˜์˜ ์ •๋ณด๋“ค์ด user database์— ๋“ค์–ด๊ฐ€๋Š”๋ฐ, ๊ทธ ์œ ์ € ์ •๋ณด๋ฅผ ๋ณดํ˜ธํ•˜๊ธฐ ์œ„ํ•œ User Model, User Schema๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ
  • Model ์ด๋ž€
    • Schema๋ฅผ ๊ฐ์‹ธ์ฃผ๋Š” ์—ญํ• 
  • Schema ๋ž€
    • ์ƒํ’ˆ์— ๊ด€๋ จ๋œ ๊ธ€์„ ์ž‘์„ฑํ•œ๋‹ค๊ณ  ํ–ˆ์„ ๋•Œ, ๊ทธ ๊ธ€์„ ์ž‘์„ฑํ•œ ์‚ฌ๋žŒ์ด ๋ˆ„๊ตฐ์ง€, ์ž‘์„ฑ์„ ํ•  ๋•Œ post์˜ ์ด๋ฆ„์ด ๋ญ”์ง€ ์•Œ์•„์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๊ทธ ์ด๋ฆ„์— ๋Œ€ํ•œ ํƒ€์ž…์€ ๋ญ”์ง€, ๋“ฑ๋“ฑ์„ ์ง€์ •ํ•˜๋Š” ๊ฒƒ
    • ์ •๋ณด๋“ค์„ ์ง€์ •ํ•ด์ฃผ๋Š” ๊ฒƒ

 

1. ๋ชจ๋ธ์„ ์ƒ์„ฑํ•  ์ƒˆ๋กœ์šด ํด๋” ๋งŒ๋“ค๊ธฐ

1) models ๋ผ๋Š” ์ƒˆ๋กœ์šด ํด๋” ์ƒ์„ฑ


2) models ๋‚ด์— User.js ๋งŒ๋“ค๊ธฐ

 

2. User.js์— ์Šคํ‚ค๋งˆ ์ž‘์„ฑ

const mongoose = require('mongoose')

const userSchema = mongoose.Schema({
    name: {
        type: String,
        maxlength: 50
    },
    email: {
        type: String,
        trim: true,  // ๋นˆ์นธ์„ ์—†์• ์ฃผ๋Š” ์—ญํ• 
        unique: 1
    },
    password: {
        type: String,
        minlength: 5
    },
    lastname: {
        type: String,
        maxlength: 50
    },
    role: {  // user๊ฐ€ ๊ด€๋ฆฌ์ž๊ฐ€ ๋  ์ˆ˜๋„ ์žˆ๊ณ  ์ผ๋ฐ˜์œ ์ €๊ฐ€ ๋  ์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ
        type: Number,  // ์˜ˆ๋ฅผ ๋“ค์–ด, number๊ฐ€ 1์ด๋ฉด ๊ด€๋ฆฌ์ž, 0์ด๋ฉด ์ผ๋ฐ˜์œ ์ €
        default: 0
    },
    image: String,
    token:{
        type: Number
    }, 
    tokenExp: {  // token์ด ์œ ํšจํ•˜๋Š” ๊ธฐ๊ฐ„
        type: Number
    }
})

const User = mongoose.model('User', userSchema)  // ๋ชจ๋ธ์ด ์Šคํ‚ค๋งˆ ๊ฐ์‹ธ์ฃผ๊ธฐ

module.exports = { User }  // ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ export


โ˜… ๋”ฐ๋ผํ•˜๋ฉฐ ๋ฐฐ์šฐ๋Š” ๋…ธ๋“œ, ๋ฆฌ์•กํŠธ ์‹œ๋ฆฌ์ฆˆ - ๊ธฐ๋ณธ๊ฐ•์˜ ํด๋ก ์ฝ”๋”ฉ ์ž…๋‹ˆ๋‹ค.