Nodejs, express, MongDB를 이용한 CRUD(2)_모델링
User
email : string/trim/unique/required
name : string/trim
password(암호화 x) string/최소 4글자 이상
Board
title : String/require
Content : String/require
user : objectId/ref:'User'
Likes : [objectId/ref:'User']
Comment
content: String
user : objectId/ref:'User'
board: objectId/ref:'Board'
Parent_comment:ObjectId/ref:'Comment'
re_comments:[objectId/ref:'Comment']
Like
User : objectId/ref:'User'
Board: objectId/ref:'Board'
Model/User.js
const UserSchema = new Schema({ email: { type: String, trim: true, unique: true, required: true, }, name: { trim: true, type: String, }, password: { type: String, validate: [ function(password){ return password.length >= 4; }, 'Password should be longer than 4 Charters' ] } });
Model/board.js
const boardSchema = new Schema({ //제목 title: { type: String, require: true, }, //내용 content: { type: String, require: true, }, //유저 user: { type:Schema.Types.ObjectId, ref:'User' }, //공개 비공개 active: { type: Number, enum: [0, 1], default: 0 }, //댓글 comments: [{ type:Schema.Types.ObjectId, ref:'Comment' }], //좋아요 유저 likes: [{ type:Schema.Types.ObjectId, ref:'User' }] });
model/Comment.js
const CommentSchema = new Schema({ content: String, user: { type: Schema.Types.ObjectId, ref: 'User' }, board: { type: Schema.Types.ObjectId, ref: 'Board' }, parent_comment: { type: Schema.Types.ObjectId, ref: "Comment", default: null }, re_comments:[{ type: Schema.Types.ObjectId, ref: 'Comment', default: null }] });
model/Like.js
const LikeSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User', }, board: { type: Schema.Types.ObjectId, ref: 'Board' } });
여기서 자주 사용된 것은 ref(외래키)설정해주는 것이다. ref를 이용해서 모델링을 하게 되면 만약 하나의 모델객체를 참조를 해주면 자동으로 해당하는 user._id값이 들어가게 된다.
그리고 type: 외에도 다양한 설정이 가능하다. Unique, enum, date 등 설정이 가능하다.
하지만 ref 외래키를 이용했지만 mongoose에서는 cascade(계단식) 설정은 불가능 하기 때문에 따로 middleware를 통하여 구현을 해야한다. 이 내용은 다음에 알아보자.
대댓글
대댓글 기능을 구현하기 위해서 Comment 모델에서 parent_comment 통해서 대댓글의 부모를 외래키를 뒀으며, re_comment에는 부모 댓글에 달린 댓글들을 이어줄 수 있도록 참조키를 두었다. 이를 통하여 부모 댓글을 통하여 대댓글들을 불러 올 수 있도록 작성하였다. 만약 댓글에 parent_comment 값이 없다면 이 댓글은 parent값이라는 것을 확인 할 수 있을 것이다.
github_page : https://github.com/gmldbd94/node_express_mongoDB
from http://gmldbd94.tistory.com/17 by ccl(A) rewrite - 2020-03-07 09:54:14
댓글
댓글 쓰기