DB를 위한 댓글 스키마 생성하기

Time Saver 2020. 11. 16. 14:30

github.com/bang-gui/blog

 

bang-gui/blog

나의 리액트 페이지. Contribute to bang-gui/blog development by creating an account on GitHub.

github.com

댓글 스키마를 검색해보다가 설명이 잘나와 있는 포스트가 있어서 사용해 보려한다.

github에 오픈 소스로 올려 놓았지만 출처를 남긴다.

www.a-mean-blog.com/ko/blog/Node-JS-%EC%B2%AB%EA%B1%B8%EC%9D%8C/%EA%B2%8C%EC%8B%9C%ED%8C%90-%EB%A7%8C%EB%93%A4%EA%B8%B0-%EA%B3%A0%EA%B8%89/%EA%B2%8C%EC%8B%9C%ED%8C%90-%EB%8C%93%EA%B8%80-%EA%B8%B0%EB%8A%A5-%EB%A7%8C%EB%93%A4%EA%B8%B0-1-%EC%93%B0%EA%B8%B0-%EB%B3%B4%EA%B8%B0

 

Node JS 첫걸음/게시판 만들기(고급): 게시판 - 댓글 기능 만들기 1 (쓰기, 보기) - A MEAN Blog

게시판에 '댓글 기능'을 추가해 봅시다. 지금까지의 강의를 통해 주소록정보(contact), 게시물(post), 이용자(user)들의 CRUD 기능을 만들어 보았는데요, 댓글 기능역시 이들과 같은 CRUD 기능이지만 이

www.a-mean-blog.com

// models/Comment.js

var mongoose = require('mongoose');

// schema
var commentSchema = mongoose.Schema({
  post:{type:mongoose.Schema.Types.ObjectId, ref:'post', required:true},
  author:{type:mongoose.Schema.Types.ObjectId, ref:'user', required:true},
  parentComment:{type:mongoose.Schema.Types.ObjectId, ref:'comment'}, // 대댓글
  text:{type:String, required:[true,'text is required!']},
  isDeleted:{type:Boolean}, // 대댓글
  createdAt:{type:Date, default:Date.now},
  updatedAt:{type:Date},
},{
  toObject:{virtuals:true} // 대댓글
});

commentSchema.virtual('childComments') // 대댓글
  .get(function(){ return this._childComments; })
  .set(function(value){ this._childComments=value; });

// model & export
var Comment = mongoose.model('comment',commentSchema);
module.exports = Comment;

post와 author는 릴레이셔널이다.

여기서는 대댓글까지도 구현이 되어있는데 나는 사용하지 않도록 하겠다.

import mongoose, { Schema } from 'mongoose';

const CommentSchema = new Schema({
  post: { type: mongoose.Types.ObjectId, ref: 'Post', required: true },
  author: { type: mongoose.Types.ObjectId, ref: 'User', required: true },
  text: { type: String, required: [true, 'text is required!'] },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date },
});

// model & export
const Comment = mongoose.model('Comment', CommentSchema);
export default Comment;

흠... 이렇게 스키마를 추가했다.

var을 const로 바꾸고 '리액트를 다루는 기술'에서 처럼 esm을 적용했다.

이제... API를 작성해보자.