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
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}`));
});
Making a function(method) for the model.
schema.static("staticName", function(document) {
return
}
then you can youse the static through Model.
Model.staticName(document);
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.
When you want to create, save, or edit something on the backend, POST request is required. There are several requirements.
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")
name
must be created.method="post"
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.
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.