댓글 스키마도 만들어봅시다.

    schemas/comment.js

    const mongoose = require('mongoose');
    
    const { Schema } = mongoose;
    const { Types: { ObjectId } } = Schema;
    const commentSchema = new Schema({
      commenter: {
        type: ObjectId,
        required: true,
        ref: 'User',
      },
      comment: {
        type: String,
        required: true,
      },
      createdAt: {
        type: Date,
        default: Date.now,
      },
    });
    
    module.exports = mongoose.model('Comment', commentSchema);

    commenter 속성만 보면 됩니다. 자료형이 ObjectId입니다. 옵션으로 ref 속성의 값이 User로 주어져 있습니다. commenter 필드에 User 스키마의 사용자 ObjectId가 들어간다는 뜻입니다. 나중에 몽구스가 JOIN과 비슷한 기능을 할 때 사용됩니다.

    Note ≣ 컬렉션 이름 바꾸기

    몽구스는 model 메서드의 첫 번째 인수로 컬렉션 이름을 만듭니다. 첫 번째 인수가 User라면 첫 글자를 소문자로 만든 뒤 복수형으로 바꿔서 users 컬렉션을 생성합니다. Comment라면 comments 컬렉션이 됩니다. 이러한 ‘강제 개명’이 싫다면 세 번째 인수로 컬렉션 이름을 줄 수 있습니다.

    mongoose.model('User', userSchema, 'user_table');

    이제 users 컬렉션 대신 user_table 컬렉션이 생성됩니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.