I’m really trying to have one picture per movie but is currently not working, I’m using multer to achieve this but is the first time I’m doing it and path is undefined for some reason.
const { Movie, validate } = require("../models/movie");
const { Genre } = require("../models/genre");
const auth = require("../middleware/auth");
const admin = require("../middleware/admin");
const validateObjectId = require("../middleware/validateObjectId");
const moment = require("moment");
const multer = require ("multer");
const express = require("express");
const router = express.Router();
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'img/');
},
filename: function(req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if(file.mimetype === 'image/jpg' || file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') {
cb(null, true);
} else {
cb(null, false);
}
}
const upload = multer({
storage: storage,
limits: { fileSize: 1024*1024*5 },
fileFilter: fileFilter
});
router.get("/", async (req, res) => {
const movies = await Movie.find()
.select("-__v")
.sort("name");
res.send(movies);
});
router.post("/", upload.single('movieImg'), [auth], async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findById(req.body.genreId);
if (!genre) return res.status(400).send("Invalid genre.");
const movie = new Movie({
title: req.body.title,
genre: {
_id: genre._id,
name: genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate: req.body.dailyRentalRate,
movieImg: req.file.path, //where the error is comming from
publishDate: moment().toJSON()
});
await movie.save();
res.send(movie);
});
module.exports = router;