1

I'm trying to create a route that save the user information along with the image and the route working with the file but in this case the image is a optional one. without the file in the request its show error.

unhandledRejection

TypeError Cannot read property 'originalname' of undefined

this is my middleware function

    const upload = multer({
        storage: multers3({
            s3,
            bucket: process.env.BUCKET_NAME,
            contentType: multers3.AUTO_CONTENT_TYPE,
            acl: 'public-read',
            metadata: (req, file, cb) => {
                cb(null, {
                    fieldname: file.fieldname,
                })
            },
            key: (req, file, cb) => {
                cb(null, file.originalname)
            },
        }),
        fileFilter: function (req, file, callback) {
            var ext = path.extname(file.originalname)
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
                return callback(new Error('Only images are allowed'))
            }
            callback(null, true)
        },
        limits: {
            fileSize: 1024 * 1024,
        },
    }).single('file')

this is my route


    router.post('/user/book',uploadfile, async (req, res) => {
        
        const user = await SlotUser.findOneAndUpdate(
            {
                _id: mongoose.Types.ObjectId(req.id),
            },
            {
                $push: {
                    tickets: {
                        eid: req.body.event_id,
                        event_name: req.body.event_name,
                        user_name: req.body.user_name,
                        slot_duration: req.body.slot_duration,
                        date: req.body.slot_date,
                        sid: req.body.sid,
                        start_time: req.body.slot_start_time,
                        end_time: req.body.slot_end_time,
                        attachment:process.env.SPACE_DOMAIN + req.file.originalname,// req file original name
                        description: req.body.description,
                        available: false,
                        status: 'booked',
                    },
                },
            }
        )
        
    
        res.json(user)
    })

can you help me to skip the upload middleware when the file is empty or not attached

NeNaD
  • 18,172
  • 8
  • 47
  • 89
Venkat Cpr
  • 153
  • 1
  • 11

1 Answers1

0

You can do this:

attachment: req.file ? process.env.SPACE_DOMAIN + req.file.originalname : null,

This will check if the file exists, and in case it does it will save it properly. In case it does not, it will save it as null.

NeNaD
  • 18,172
  • 8
  • 47
  • 89