vaildation
혹시 비디오모델과
post upload의 object 데이터 형태가 다르게되면
await video.create() 요부분에서
비디오가 생성되지 않아 계속 기다리게되고 해당 부분 코드에서 멈춤
다음 명령어인 return res.redirect("/"); 리턴 할 수 없게된다.
에러가 발생했을 때 위해서 --> try,catch 문
export const postUpload = async (req, res) => {
const { title, descirption, hashtags } = req.body;
try{
await video.create({ // 이부분에 문제가 없으면
title,
descirption,
hashtags: hashtags.split(",").map((word) => `#${word}`),
meta: {
views: 0,
rating: 0,
} //from을 완성하고
});
return res.redirect("/"); //video로 리다이렉트
}catch (error) { //에러가 있다면
console.log(error); //콘솔에 에러를 찍어주고, 에러가있더라도 리턴 해야함
return res.render("upload", { //다시 업로드화면 렌더링
pageTitle: "Upload video",
errorMessage: error._message, //rendering할 때 errorMessage도 같이 렌더링 error console에 찍힌 메세지임
});
}
template upload 코드
extends base
block content
if errorMessage //렌더링할 때 템플릿 변수로 보내주고있음
span= errorMessage
form(method ="POST")
input(placeholder="Title", required, type="text", name="title")
input(placeholder="Descirption", required, type="text", name="descirption")
input(placeholder="Hashtags, separated by comma.", required, type="text", name="hashtags")
input(type="submit", value ="Upload video")
-----------------------------------------
awiat video.create({
createdAt: Date.now() 매번 동영상을 만들 때마다 date.now() 하고싶지않음 -->default 설정
default로 설정 해 버리면 이 프로퍼티는 아예 생성, 적지 않아도 됨
})
비디오 schema에서 데이터 형식 입력시 default 설정
createdAt: { type: Date, required: true, default: Date.now, },
Date.now()는 지금 당장 실행 시키는 것, 지금 시간을 알고 싶진 않음 Date.now라고 적으면
몽구스가 알아서 비디오 생성 할 때Date.now()로 실행 시켜줌
다른예
비디오 생성시에 매번
meta: {
views: 0,
rating: 0,
} 이 값을 적지말고
videoschema에서
meta: {
views: {type: Number, default: 0 },
rating: {type: Number, default: 0 },
}
다음과 같이 적어 줌
--------------------------------------------------------------------------
데이터에 대한 구체적인 설정은 매우 중요하다.
const videoSchema = mongoose.Schema({
title: { type: String, required: true, uppercase: true, trim: true, maxLength: 80 },
description: { type: String, required: true, trim: true, minLength: 20 },
template인 upload pug에 들어가서
extends base
block content
if errorMessage
span= errorMessage
form(method ="POST")
input(placeholder="Title", required, type="text", name="title" minlength=20)
input(placeholder="Descirption", required, type="text", name="description" maxlength=80)
html 속성으로 넣으면 브라우저가 도와줌
브라우저에서 하면되는데 왜 굳이 database에 알려줘야 하나?
두개다해야함
하나는 사용자를 위해
하나는 시스템 보호를 위해