1. DeprecationWarning
- findByIdAndUpdate를 사용하니 DeprecationWarning라는 경고가 발생함
- 경고 메시지에 나온데로 useFindAndModify를 db에 추가하면 됨
// db.js
mongoose.connect("mongodb://127.0.0.1:27017/wetube", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
});
- mongoose가 오래된 것들을 처리하는 방법이라 시키는데로 하면 됨
2. Middleware를 통한 Hashtag 처리
- 현재는 영상을 업로드하거나 수정할 때, model에 저장하기 전에 hashtag를 처리함
- 하지만 영상을 저장하기 전에 여러가지를 해야 하는데, 예로 회원가입을 한다고 생각하면, 유저를 생성하기 전에 email이 존재하는지 확인함
- comment에 비속어 필터링이 있을 수 있으며 고려할게 많음
- 현재의 hashtag 처리도 저장 하기 전 #나 콤마가 있는지 체크를 하는데, 이건 복붙하기 꺼려짐
- mongoose의 middleware를 통해 이런 것들을 저장하기 전에 미리 처리할 수 있음
- express의 middleware와 비슷함
- https://mongoosejs.com/docs/middleware.html
Mongoose v8.8.0: Middleware
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins. Mongoose has 4 types of middleware: document middl
mongoosejs.com
- middleware에 여러가지가 있지만 중요한 것은 얘네들이 끼어들 틈을 만들어 주며 흐름을 방해하지 않음
- 우리가 영상을 업로드하고 업데이트 하기전에 프로세스를 잠시 중단하고 hashtag 같은 것들을 깔끔히 정리한 다음, 하던걸 마저 함
2. Middleware
- model이 생성되기 전에 middleware를 만들어야 하며, middleare로 호출될 async function을 보냄
// Video.js
videoSchema.pre("save", async function () {
console.log("we r about to save: ", this);
});
const Video = mongoose.model("Video", videoSchema);
// result
we r about to save: {
meta: { views: 0, rating: 0 },
createdAt: 2024-11-04T08:46:39.205Z,
hashtags: [ '#for', '#real', '#now' ],
_id: 67288a0f557fa20840b80065,
title: 'hashtag',
description: '1234567891011121314151617181920'
}
- this는 우리가 저장하고자 하는 문서(Video)를 가르킴
- controller에서 hashtag를 처리하던 split과 map을 지우고, 새로운 영상을 업로드하면 hashtag가 입력받은 string을 mongoose가 array로 바꿈 - 하지만 나눠지지 않고, 단순히 입력받은 문자열을 array의 첫번째 element로 저장 - 이제 hashtags array의 첫 element가 format되는 방식을 바꿈
// Video.js
videoSchema.pre("save", async function () {
this.hashtags = this.hashtags[0]
.split(",")
.map((word) => (word.startsWith("#") ? word : `${word}`));
});
'개발 > Node.js' 카테고리의 다른 글
Delete and Search Video (0) | 2024.11.05 |
---|---|
Mongoose Middleware(2) (0) | 2024.11.04 |
Edit Video (0) | 2024.11.04 |
More Schema, Router 수정 (0) | 2024.11.04 |
실제 데이터를 입력해보기 (0) | 2024.11.04 |