0
votes

I run into a problem creating my first RESTapi app.

I have a multer module included to get a file uploaded using form and everything works great until I provide the file.

If the file is not provided then my app crashes, so if someone will trigger a post route in my API to create a new entity(using curl for example) the app will crash.

It seems like file is always required when using multer to upload it.

My router.post looks like this:

router.post('/movies', upload.single('image'), function(req, res, next) {
var movie = new Movie(req.body);
movie.fileName = req.file.filename;
movie.save(function(err, movie){
    if(err) return next(err);
    res.json(movie);
}); });

So the question is:

Is it possible to leave the "file" field empty and still process saving data to db simply without fileName field? Thank you in advance!

1
can you upload your schema code....... - vighanesh mandavkar

1 Answers

1
votes

It's not that multer requires a file - you just need to guard against req.file being undefined. You're referencing req.file.filename without checking whether req.file exists. Simply check whether it exists and if so set the filename on the movie:

router.post('/movies', upload.single('image'), function(req, res, next) {
  var movie = new Movie(req.body);
  if(req.file) movie.fileName = req.file.filename;
  movie.save(function(err, movie){
      if(err) return next(err);
      res.json(movie);
  });
});