[Node JS] #5.3 CRUD (1)
#1. Create
1.FormとControllerのコミュニケーション
Upload.pug
form(method="POST")
input(name="title", placeholder="Title", required, type="text")
input(name="description", placeholder="Description", required, type="text")
input(name="hashtags", placeholder="Hashtags, separated by comma.", required, type="text")
input(type="submit", value="Upload Video")
controller.jsexport const postUpload = (req, res) => {
const { title, description, hashtags } = req.body;
console.log(title, description, hashtags);
return res.redirect("/");
};
2. Create Document
Controller.js
const video = new Video({
title,
description,
createdAt: Date.now(),
hashtags: hashtags.split(",").map(word => `#${word}`),
meta: {
views: 0,
rating: 0,
},
});
3. Save Document in Database
1.オブジェクトの保存
await video.save();
2.Createの実行
await Video.create({
title,
description,
createdAt: Date.now(),
hashtags: hashtags.split(",").map((word) => `#${word}`),
meta: {
views: 0,
rating: 0,
},
});
4. Try, Catch
try {
const { title, description, hashtags } = req.body;
await Video.create({
title,
description,
createdAt: Date.now(),
hashtags: hashtags.split(",").map((word) => `#${word}`),
meta: {
views: 0,
rating: 0,
},
});
return res.redirect("/");
} catch (error) {
return res.render("upload", {
pageTitle: "Uplaod Video",
errorMessage: error._message,
});
}
#2. READ
1. Router
[0-9a-f]{24}
2. Find
const { id } = req.params;
const video = await Video.findById(id);
Reference
この問題について([Node JS] #5.3 CRUD (1)), 我々は、より多くの情報をここで見つけました https://velog.io/@choiish98/Node-JS-5.4-CRUD-1テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol