# 6.23 -24 middleware (in mongoose) , Statics

이원규·2022년 6월 21일
0

Itube

목록 보기
22/46

DB reset하는 법.

  1. 몽고 사용하기


    mongo

  2. 내가 가진 db 보기


    show dbs

  3. 현재 사용 중인 db 확인


    db

  4. 사용할 db 선택하기


    use dbName
    (현재 수업에서는 use wetube)

  5. db 컬렉션 보기


    show collections

  6. db 컬렉션 안에 documents 보기

    
 db.collectionName.find()
    (현재 수업에서는 db.videos.find())

  7. db 컬렉션 안에 documents 내용 모두 제거하기


    db.collectionName.remove({})
    (현재 수업에서는 db.videos.remove({}))


Middware(hook):

mongoose middleware MDN
-> mongoose의 기능 중, 뭔가를 저장하거나 업데이트 하기 전에 이거저거 하라고 시킬 수 있음. 우리는 이걸 hashtags에 적용할 것임. express(ex: morgan)에서 본 middleware와 같다고 보면 됨.(pre, post, hook이 있음.)
-> object가 저장 혹은 업데이트 되기 전에 무엇인가를 먼저 하고 나머지(비디오 저장 혹은 업데이트)를 처리할 수 있게 해줌.

-> document에 무슨 일이 일어나기 전이나 후에 middleware를 적용할 수 있음. 예를 들면 save(or Update)를 하기 전후로 middleware를 적용하거나 function을 실행시킬 수 있음. express의 middleware과 같이 흐름을 방해하지 않음.
-> middleware의 종류(아래 사진과 같이 종류가 있음). 이 middleware에서는 this라는 인수를 갖는데, 이것은 우리가 작업을 실행해주는 문서를 가르킴.

-> middelware은 반드시! model이 형성되기 전에 만들어야함. 즉, Schema와 model사이에 만들어줘야함. 이 뜻은 model이 들어있는 js에서 middleware를 만들어줘야 한다는 뜻과도 같음.

-> middleware안에 실행할 함수는 =>(화살표)를 쓰면 안됨. 대신 "function(){}"이걸로 써줘야함!

  • Video.js for save(create video)
videoSchema.pre('save', async function(){
    //console.log("We are about to save: ", this);//내가 작업하는 문서의 내용(여기는 video)를 출력해줌
    //this.title = "hahahah";//이런 식으로 문서의 내용을 수정할 수도 있음.
    this.hashtags = this.hashtags[0].split(",").map((word) => word.startsWith("#") ? word:`#${word}`);// 여기서 hashtags[0]를 한 이유: hashtags input에 내용을 적고 save하면, 초기에 this.hashtags = ["for, new, hash, tag"] 이런 형태의 하나의 string을 가진 array로 나올 것이기 때문에.
});

-> 이게 멋지긴 하지만, 이 middleware는 update & upload(save) 둘 다에 쓰일 순 없음.
(왜냐하면, findOneAndUpdate에서는 (이거는 postEdit에 쓰이는 것) this를 쓸 수 없음. 즉, 수정하고있는 문서에 접근할 수가 없다는 뜻임.)

1. Update & save에 쓸 수 있는 방법(middleware 사용 x)

  • Video.js(model.js)에서 함수를 정의하고 컨트롤러에서 import해서 사용하기
    Video.js
export const formatHashtags = (hashtags) => 
hashtags.split(",").map((word) => (word.startsWith("#") ? word : `#${word}`));

videocontroller

import {formatHashtags} from "../models/Video";

export const postUpload = async(req,res) => {
    // here we will add a video to the videos array.
    const { title, description, hashtags } = req.body;
    try{
        await Video.create({//Video.create: video를 생성하고, DB에 저장함.
            title:title,
            description:description,
            hashtags:hashhash(hashtags), //-> function을 이용
        });
        return res.redirect("/");
    }
    catch(error){
        console.log(error);
        return res.render("upload",{
            pageTitle:"Upload Video",
            errorMessage: error._message,
        });
    }
}

2. Statics이용

Statics (Schema와 model사이에 넣어줘야함.)

Statics MDN
-> model에 쓰일 function을 만들 수 있음.
-> model만 import해주면 내장함수로서 사용할 수 있음.(따로 import필요 X)
-> 필요한 것: Schema.static, function, 만들고자 하는 static이름.
-> 형태: videoSchema.static(static이름, 함수)

  • Video.js(model.js)
videoSchema.static('formatHashtag', function(hashtags){
    return hashtags.split(",").map((word) => (word.startsWith("#") ? word : `#${word}`))
});
  • videoController
//추가(수정) 코드
hashtags:Video.formatHashtag(hashtags),

//최종 코드
export const postUpload = async(req,res) => {
    // here we will add a video to the videos array.
    const { title, description, hashtags } = req.body;
    try{
        await Video.create({//Video.create: video를 생성하고, DB에 저장함.
            title:title,
            description:description,
            hashtags:Video.formatHashtag(hashtags),
        });
        return res.redirect("/");
    }
    catch(error){
        console.log(error);
        return res.render("upload",{
            pageTitle:"Upload Video",
            errorMessage: error._message,
        });
    }
}

mixin수정 -> hashtag보이도록 해줄것임

mixin video(video)
    div
        h4 
            a(href=`/videos/${video.id}`)=video.title
        p=video.description 
        ul 
            each hashtag in video.hashtags
                li=hashtag
        small=video.createdAt
        hr 
profile
github: https://github.com/WKlee0607

0개의 댓글