#TIL
Multer: middleware for handling file uploads
- this middleware needs to be passed before your handler function
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
- Also note, by using the multer middleware, you can access the file via
req.file
- Keep in mind that unlike other parts of the form fields where if you designate a specific name (e.g.
<input name="title">
) you can access it viareq.body.specific-name
(in my example, it would bereq.body.title
)- you access the uploaded file object viareq.file
. - If you are using multer for your file upload middleware, be sure to put
enctype="multipart/form-data"
as your form attribute - OR ELSE IT WILL NOT WORK
Another reminder about MongoDB:
- If you are trying to add a field/data to your document that does not exist in your Model Schema, that information will not be added. Aka, model schemas “guard” how your documents look like.
- For example: today I was trying to add fileUrl to my videos collection; I was able to verify that I successfully got the fileUrl from my multer middleware via
req.file
object. However, when I looked at the video collections in my MongoDB account, I noticed that fileUrl was not added to the video object. - Problem: I found out that I did pass the
req.file.path
information to theawait Video.create()
function.
export const postUpload = async (req, res) => {
const { path: fileUrl } = req.file;
const { title, description, tags } = req.body;
try {
await Video.create({
title,
description,
hashtags: tags,
fileUrl,
});
return res.redirect(`/`);
- However, I realized that I never updated my Video Model schema to include fileUrl as a datafield.
import mongoose from 'mongoose';
const videoSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true, maxLength: 80 },
description: { type: String, trim: true },
tags: [{ type: String }],
});
- Solution: To ensure the documents in the videos collection all have path Urls stored, I had to update my videoSchema to:
import mongoose from 'mongoose';
const videoSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true, maxLength: 80 },
description: { type: String, trim: true },
tags: [{ type: String }],
fileUrl: { type: String, required: true }
});
- Personally, I love how Mongoose schemas safeguard the structure of inserted documents, but this means that you HAVE to update the Model Schemas themselves as you add more data fields.