🎣 Hooks (Middleware)

PussinSocksΒ·2022λ…„ 7μ›” 23일
0

CloneCoding

λͺ©λ‘ 보기
14/20

Middleware in Mongoose

Middleware is basically intercepts request and do something inside of the middleware and call next() to pass the request. (Ex: Morgan middleware)
Middleware should be created before model is built.

const modelSchema = {};

modelSchema.pre("save", async function(){
});

this

this referse to the document that we want to manipulate.

videoSchema.pre("save", async function(){
    this.hashtags = this.hashtags[0]
    .split(",")
    .map((word) => (word.startsWith("#") ? word : `#${word}`));
});

static

Making a function(method) for the model.

schema.static("staticName", function(document) {
	return
}

then you can youse the static through Model.

Model.staticName(document);

Why do we need the middleware?

Middleware can intercepts the data before it is send to the model. With this in mind we can manipulate the data before it gets saved or updated. and Also minimize the amount of repeated codes

This can benefit on encrypting password of the user account and etc.


Middleware for POST

When you want to create, save, or edit something on the backend, POST request is required. There are several requirements.

  1. Forms in the view
extends base.pug

block content 
    h4 Update video
    form(method="POST")
        input(name="title", 
              placeholder="New title", 
              value=video.title, required)
        input(name="description", 
              placeholder="Description", 
              required, type="text", 
              minlength=20, 
              value=video.description) 
        input(name="hashtags", 
              placeholder="#hashtags separated by comma", 
              required, 
              type="text", 
              value=video.hashtags.join()) 
        input(type="submit" 
              value="Save")
  • When you make a form in a view, name must be created.
  • form should be set as method="post"
  1. When the information in the form is submitted, the HTML form information will be translated into JavaScript object(req.body form), due to app.use(express.urlencoded({exntended: true})); and send to URL.

  2. The request will be go through the router,

export const videoUpload.router("/upload")
  .get(getUpload)
  .post(postUpload); //URL go through this

and get to the designated controller where the req.body can be understood.


export const postUpload = async (req, res) => {
	const {title, description, hashtags} = req.body;
	const newVideo = {
      title,
      description,
      hashtags,
   };
  videos.push(newVideo);
  return res.redirect("/");
};
// Again, req.body is the way to get the data which user is posting.
profile
On a journey to be a front-end developer

0개의 λŒ“κΈ€