[Node JS] #5.3 CRUD(2)

2562 단어 node jsnode js

#. Upload

1. Control 404 Error

  • When can’t find object, Use error 404
  • Implement
if (!video) {
  return res.render("404", { pageTitle: "Video not found." });
} else {
  return res.render("watch", { pageTitle: video.title, video });
}

2. GET

  • Control get URL
  • It is not different with GET Upload URL
  • Implement
export const getEdit = async (req, res) => {
  const { id } = req.params;
  const video = await Video.findById(id);
  if (!video) {
    return res.render("404", { pageTitle: "Video not found." });
  }
  return res.render("edit", { pageTitle: `Editing ${video.title}`, video });
};

3. POST

  • Get form data from req.body;
  • Save data into object
  • Implement
export const postEdit = async (req, res) => {
  const { id } = req.params;
  const { title, description, hastags } = req.body;
  const video = await Video.findById(id);
  if (!video) {
    return res.render("404", { pageTitle: "Video not found." });
  }
  video.title = title;
video.description = description;   
video.hashtags = hashtags
    .split(",")
    .map((word) => (word.startsWith("#") ? word : `#{word}`));
  await video.save();
  return res.redirect(`/videos/${id}`);
};

4. findOneAndUpdate()

  • It is provided by mongoose with model.
  • Need 2 props, the id of the video to update, the update info
  • Implement
export const postEdit = async (req, res) => {
  const { id } = req.params;
  const { title, description, hastags } = req.body;
  const video = await Video.findById(id);
  if (!video) {
    return res.render("404", { pageTitle: "Video not found." });
  }
  await Video.findByIdAndUpdate(id, {
    title,
    description,
    hastags: hashtags
      .split(",")
      .map((word) => (word.startsWith("#") ? word : `#{word}`)),
  });
  return res.redirect(`/videos/${id}`);
};

5. Exists()

  • Find object with condition (filter=which is mean any condition)
  • Return true or false
  • Implement
const video = await Video.exists({ _id: id });
  if (!video) {
    return res.render("404", { pageTitle: "Video not found." });
}

6. Check

  • Middleware: Before update or save anything, gonna do something

좋은 웹페이지 즐겨찾기