model(User, Video)

김종민·2022년 11월 2일
0

Youtube

목록 보기
16/23

들어가기
Model을 정리해본다


1. src/models/User.js

import mongoose from 'mongoose'
import bcrypt from 'bcrypt'

// export const formatHashtags = (hashtags) =>
//   hashtags.split(',').map((word) => (word.startsWith('#') ? word : `#${word}`))

const userSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  avatarUrl: String,
  socialOnly: { type: Boolean, default: false },
  username: { type: String, required: true, unique: true },
  password: { type: String },
  name: { type: String },
  location: String,
  videos: [
    { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Video' },
  ],
  ///user를 load할떄 ,populate.videos하면,
  ///user와 관련된 video들을 모두 불러들일 수 있음.
})

userSchema.pre('save', async function () {
  // console.log('111', this.password)
  if (this.isModified('password')) {
    this.password = await bcrypt.hash(this.password, 5)
  }
  // console.log('222', this.password)
})
--->password가 save될때, hash화 시켜서 save하는데,
--->isModified로 password가 edit된 경우에만,
--->다시 hash화 해서 save하게 한다.
--->이부분을 설정하지 않으면, username이나, email Edit시,
--->password가 다시 hash화 되어버림.

const User = mongoose.model('User', userSchema)
export default User

2. src/models/Video.js

import mongoose from 'mongoose'

// export const formatHashtags = (hashtags) =>
//   hashtags.split(',').map((word) => (word.startsWith('#') ? word : `#${word}`))

const videoSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    upppercase: true,
    trim: true,
    maxLength: 140,
  },
  fileUrl: { type: String, required: true },
  description: String,
  createdAt: { type: Date, required: true, default: Date.now },
  hashtags: [{ type: String, trim: true }],
  meta: {
    views: { type: Number, default: 0, required: true },
    rating: { type: Number, default: 0, required: true },
  },
  owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
})
  ///video를 load할떄 ,populate.owner,
  ///video와 관련된 user들을 모두 불러들일 수 있음.

videoSchema.static('formatHashtags', function (hashtags) {
  return hashtags
    .split(',')
    .map((word) => (word.startsWith('#') ? word : `#${word}`))
})

// videoSchema.pre('save', async function () {
//   console.log('we saving this.', this)
//   this.hashtags = this.hashtags[0]
//     .split(',')
//     .map((word) => (word.startsWith('#') ? word : `#${word}`))
// })

const Video = mongoose.model('Video', videoSchema)
export default Video
profile
코딩하는초딩쌤

0개의 댓글