Update
export const videoEditSave: ExpressRouter = async (req, res) => {
const { id } = req.params;
const { title, description, hashTags } = req.body;
const videoId = id.replace("/edit", "");
const video = await contentsModel.exists({ _id: videoId });
if (!video) {
return res.render("404", {
pageTitle: `Not Found`,
});
}
await contentsModel.findByIdAndUpdate(videoId, {
title,
description,
hashTags: hashTags.split(",").map((word: string) => `#${word}`),
});
return res.redirect(`/video`);
};
- Mongoose - Pre
Pre는 새로운 객체를 저장할때 저장하기전 스키마의 행위를 지정해주는 미들 웨어이다.
예를 들면 해쉬태그를 작성한다면 input의 값을 쉼표로 나누어 작성했을 경우 하나의 객체로 만들어주며 하나의 객체 앞에 '#'을 붙여주는 행위를 한다 가정했을 때 아래와 같이 문장을 작성할 수 있다.
Pre에는 두가지 인자를 받는데 첫번 째로는 방식이며 지정되어 있다. 두번째는 function을 입력해주면 된다.
contentsSchema.pre("save", async function () {
this.hashTags =
this.hashTags &&
(this.hashTags[0] as string).split(",").map((word) => `#${word}`);
});
- Mongoose - Static
Static은 Pre와 비슷하지만 직접 function handler를 만들어준다고 생각하면 쉽다.
contentsSchema.static('hashFormat', function(hashTags){
return hashTags.split(",").map((word:string) => `#${word}`)
})
//type script 경우에
import mongoose, { Model } from "mongoose";
import { IVideo } from "../types/type";
interface IHashformat extends Model<IVideo> {
formatHash(hashTags: string): string[];
}
const contentsSchema = new mongoose.Schema<IVideo, IHashformat>({
contentsForm: { type: String, required: true, trim: true },
title: { type: String, required: true, trim: true, minLength: 3 },
description: { type: String, required: true, trim: true, maxLength: 30 },
createAt: { type: Date, required: true, default: Date.now() },
hashTags: [{ type: String, trim: true }],
meta: {
views: { type: Number, required: true, default: 0 },
rating: { type: Number, required: true, default: 0 },
},
});
contentsSchema.static(
"formatHash",
function formatHash(hashTags: string): string[] {
return hashTags.split(",").map((word: string) => `#${word}`);
},
);
const contentsModel = mongoose.model<IVideo, IHashformat>(
"Video",
contentsSchema,
);
export default contentsModel;
Delete
export const deleteVideo: ExpressRouter = async (req, res) => {
const { id } = req.params;
const videoId = id.replace("/delete", "");
const video = await contentsModel.exists({ _id: videoId });
if (video) {
await contentsModel.findByIdAndDelete(videoId);
res.redirect("/video");
} else {
return res.render("404", {
pageTitle: `Not Found`,
});
}
};