• db.js์—์„œ ์–ด๋–ค ์ผ์ด ์ผ์–ด๋‚˜๊ณ  ์žˆ๋Š” ์ง€ ? : mongodb์™€ ์—ฐ๊ฒฐ? mongoose์˜ ์—ญํ• ์€ ?
  • mongodb์™€ ์—ฐ๊ฒฐํ•œ db.js๋ฅผ app.js์—์„œ import ํ–ˆ๋‹ค.
  • model/Chat, model/Like ์— schema๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค.
import mongoose from 'mongoose';

const ChatSchema = new mongoose.Schema({
    message : {
        type: String,
        required : 'Message is required'
    },
    likes : [
        {
            type : mongoose.Schema.Types.ObjectId,
            ref: "Like"
        }
    ]
});

const model = mongoose.model("Chat", ChatSchema);
export default model;

ChatSchema๋ฅผ "Chat"์œผ๋กœ ์ปดํŒŒ์ผ?ํ•˜๊ณ  model์€ ๋ญ์ง€?
app.js ์—์„œ Chat Model๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ณ  ์‹ถ์€๋ฐ ์ด๋ฆ„์„ Chat์ด ์•„๋‹Œ model์„ ์ ์–ด์•ผํ•˜๋‚˜?
=> app.js์—์„œ Chat์„ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ์„ ๋•Œ, ์•„๋ž˜์ฒ˜๋Ÿผ Chat ์ด๋ฆ„์œผ๋กœ ๋ฐ”๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Œ . โŒ ๊ทผ๋ฐ ์™œ ์ด๋ฆ„์„ model๋กœ export๋ฅผ ํ•˜๋Š”์ง€๋Š” ๋ชจ๋ฅด๊ฒ ์Œ

import Chat from './models/Chat' 
import model from './models/Chat';

io.on('connection', function(socket){
    socket.on('new message', function(msg){
        // message ๋ณด๋‚ธ username, ์ข‹์•„์š” ์ˆ˜๋„ ํ•จ๊ป˜ ์ €์žฅ
        model.create({message : msg});
        io.emit('notification', msg);
    })
});
const model = mongoose.model("Chat", ChatSchema);
export default model;

module.exports = mongoose.model('Album', AlbumSchema);

์œ„์™€ ์•„๋ž˜๋Š” ๋™์ผํ•œ ํ‘œํ˜„์ด๋‹ค. mongoose instance์˜ model constructor๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ collection์˜ ์ด๋ฆ„ ex. Chat, Album ๊ณผ schema definition์˜ ์ฐธ์กฐ๋ฅผ ์ „๋‹ฌํ•œ๋‹ค.

  • โŒ const chats = Chat.find({}); ์™œ Chat์—์„œ ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋“ค์„ ๊ฐ€์ ธ์˜ค์ง€ ๋ชปํ•˜๋Š”๊ฑฐ์ง€..
  • Chat.find({}, function(err, chats){
          res.render('home', { pageTitle : 'home', chats});
      });
    ํ•˜๋‹ˆ Chat ๋ชจ๋ธ์˜ chats document๋“ค์„ ๊ฐ€์ ธ์™€์„œ chats๋กœ ์ „๋‹ฌํ•ด ์ฃผ์—ˆ๋‹ค. ์œ„์˜ X ์™€ ๋ฌด์Šจ ์ฐจ์ด๊ฐ€ ์žˆ๋Š”์ง€๋Š” ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ await, async์™€๋„ ๊ด€๋ จ ์žˆ๋Š” ๊ฒƒ ๊ฐ™๋‹ค. ์•„๋ฌดํŠผ ํ•ด๊ฒฐํ•ด์„œ ๋ฟŒ๋“ฏ!
  • Model์€ Schema ์ •์˜๋กœ ๋ถ€ํ„ฐ ์ปดํŒŒ์ผ๋œ constructor์ด๋‹ค. ๋ชจ๋ธ์˜ instance๋ฅผ document๋ผ๊ณ  ํ•œ๋‹ค. ๋ชจ๋ธ๋“ค์€ Mongodb ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋กœ ๋ถ€ํ„ฐ documents๋ฅผ ์ฝ๊ฑฐ๋‚˜ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.