Search code examples
javascriptnode.jsreactjsmongoosemulter

How can you put a default image in multer if no image is uploaded?


I'm trying to set up multer but I'm having some issues with the image, as for now, when I don't upload any image, the server gives me an error which doesn't allow me to continue. I want that even if the image is not uploaded, to still store the values in the database.

This is where I have my multer configured:

    const express = require('express');
    const router = express.Router();
    const multer  = require('multer');
    
    const Clients = require('../models/clients.js')
    
    const storage = multer.diskStorage({
      destination: (req, file, callback) => {
        callback(null, "../emaildragger/public/uploads")
      },
      filename: (req, file, callback) => {
        callback(null, file.originalname)
      }
    })
    
    const upload = multer({storage: storage})
    
    router.route('/').get((req, res) => {
        Clients.find()
        .then(client => res.json(client))
        .catch(err => res.status(400).json('Error:' + err))
    })
    
    router.route('/:id').get((req, res) => {
      Clients.findById(req.params.id)
      .then(client => res.json(client))
      .catch(err => res.status(400).json("Error" + err))
    })
    
    router.route('/add').post(upload.single("image"), (req, res) => {
      
        const newClient = new Clients({
          image: req.file.originalname,
          firstName: req.body.firstName,
          lastName: req.body.lastName,
          weight: req.body.weight,
          BMI: req.body.BMI
        })
    
        newClient.save()
        .then (() => res.json(newClient))
        .catch(err => res.status(400).json('error' + err))
    })
    
    module.exports = router

Here is my models:

    var mongoose = require('mongoose');
    
    var Schema = mongoose.Schema;
    
    var clientsSchema = new Schema(
      {
        image: 
          { type: String, required: false, default: 'Screenshot_293.png'},
        firstName: { type: String, required: true },
        lastName: { type: String, required: true },
        weight: { type: String, required: false },
        BMI: { type: String, required: false }
      }
    );
    
    
    const Clients = mongoose.model("clients", clientsSchema)
    
    
    module.exports = Clients

Solution

  • The error is in your server because you added Multer as an middleware, and later in your controller you are trying to access the originalname of the uploaded file. If you didn't send the image, then Multer will not parse and upload it, and the file will not exist. In that case you will try to access to the originalname property of something that does not exist, so your server will throw an error.

    Try to change you code like this:

    router.route('/add').post(upload.single("image"), (req, res) => {
    
       let client = {
          firstName: req.body.firstName,
          lastName: req.body.lastName,
          weight: req.body.weight,
          BMI: req.body.BMI
       }  
       if(req.file && req.file.originalname) client.image = req.file.originalname;
       
       const newClient = new Clients(client)
    
       newClient.save()
       .then (() => res.json(newClient))
       .catch(err => res.status(400).json('error' + err))
    })