Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

mongodb - Node.js, Multer. video file is saved/uploaded but validator gives an error that video field can not remain empty

I'm trying to upload a video using multer, I have a form and everything but when I click create, validator gives an error however, the file is saved in my directory as if validation was successful. I'm using mongoDB for database.

here's the validator

const { check } = require('express-validator/check');
const Video = require('app/models/VideoModel');
const path = require('path');

class videoValidator extends validator {
    
    handle() {
        return [
            check('title')
                .isLength({ min : 5 })
                .withMessage('title should be at least 5 characters'),

            check('artist')
                .not().isEmpty()
                .withMessage('artist field can not be empty'),

            check('videos')
                .custom(async (value , { req }) => {
                    if(req.query._method === 'put' && value === undefined) return;

                    if(! value)
                        throw new Error('the video field can not remain empty');

                    let fileExt = ['.webm' , '.ogg' , '.mp4' , '.avi'];
                    if(! fileExt.includes(path.extname(value)))
                        throw new Error('file extention is not supported')
                }),

    }

    
    slug(title) {
        return title.replace(/([^?-??-?a-z0-9]|-)+/g , "-")
    }
}

module.exports = new videoValidator();
question from:https://stackoverflow.com/questions/65856251/node-js-multer-video-file-is-saved-uploaded-but-validator-gives-an-error-that

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just realized I've forgotten to add convertFileToField middleware. it's working fine now

handle(req , res , next) {
        if(! req.file) 
            req.body.videos = undefined;
        else
            req.body.videos = req.file.filename;

        next();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...