Cog Factory 2020. 8. 23. 15:23

  Schema는 MongoDB의 데이터 구조다. mongoDB는 NoSQL 언어다. 그래서 관계형 데이터 언어가 아니다. mongoDB는 mongoose로 Schema를 작성해서 데이터 구조를 만들어 놓는다. Schema는 데이터가 아니다. model(=collection)을 만들고 그 model의 데이터 구조를 Schema로 작성한 것이다.

  나는 UserSchema를 작성했다. name, email과 avatarUrl은 type을 String으로 했다. githubId와 kakaoId는 type을 Number로 comments와 videos는 객체를 담을 수 있는 배열로 선언했다. User.js 이외에 Video.js와 Comment.js를 만들고 그에 따른 Schema와 model을 만들면 UserSchema가 comment와 video 객체를 가져올 수 있다. type은 mongoose.Schema.Types.ObjectId로 하고 ref는 그에 해당하는 model의 이름을 따라간다. 즉, 내가 mongoose.model('Comment', CommentSchema)라고 하면 인자로 준 Comment가 ref가 가리키는 객체의 이름이다.

// User.js
import mongoose from 'mongoose';

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  avatarUrl: String,
  githubId: Number,
  kakaoId: Number,
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Comment',
    },
  ],
  videos: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Video',
    },
  ],
});

const model = mongoose.model('User', UserSchema);

export default model;

참고 자료

소스 코드

https://github.com/zpskek/wetube-v3/commit/1b5028875a737af25d4ace6c5ad82c94523a26d8