All About CRUD - Implementing CRUD

Jun's Coding Journey·2022년 11월 12일
0

[Challenge] Youtube Clone

목록 보기
12/19

CREATE

With our models, we can start creating content by adding actual data through our controllers. Since we have a model which describes how our data will look like, we can use the object of the model on our controller which will help visually display data on the browser.

Additionally, using functionalities such as split() and map(), we control how our data should be displayed.

extends base.pug

block content
  form(method="POST")
    input(placeholder="Title", required, type="text", name="title")
    input(placeholder="Description", required, type="text", name="description")
    input(placeholder="Hashtags, separated by comma.", required, type="text", name="hashtags")
    input(type="submit", value="Upload Video")
export const postUpload = async (req, res) => {
  const { title, description, hashtags } = req.body;
  const video = new Video({
    title,
    description,
    createdAt: Date.now(),
    hashtags: hashtags.split(",").map((word) => `#${word}`),
    meta: {
      views: 0,
      rating: 0,
    },
  });
  return res.redirect("/");
};

We cannot, however, display data on the browser just buy creating a new object. Instead, we need to either use the save() or create() functionality to actually capture our data and put it on our database.

For example, if we were to use the create() function, we would need to put our target data inside the function and run the code with the async and await method. In this case, we do not need to manually create a function as JavaScript will do all that for us.

export const postUpload = async (req, res) => {
  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("/");
};

After this process, our actual data will get saved in our database for real.

profile
Greatness From Small Beginnings

0개의 댓글