asharma
asharma

Reputation: 63

Insert file with form data in mongodb using express

I was trying to upload a .mp4 file to my mongodb database with some other information. I can save the file using multer and gridfs. The code i am using for this:

// Create storage engine
const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }
                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'vid'
                };
                resolve(fileInfo);
            });
        });
    }
});
const upload = multer({ storage });

router.post('/upload', upload.single('video'), (req, res) => {
    res.json({ file: req.file });
    // res.redirect('/');
});

And for uploading file data into db i'm doing this:

//ADD VIDEO
router.post('/addVideo', (req,res) => {
    var newVideo = new Video();

    newVideo._courseId = req.body.courseId;
    newVideo._chapterId = req.body.chapterId;
    newVideo.name = req.body.name;
    newVideo.des = req.body.des;

    newVideo.save((err,note) => {
        if(err){
            res.status(404).send({err: "Something went wrong"})
        } else {
            res.status(200).send({err: "Your note has been added!!"})
        }
    })
})

Both parts are working well but i have to make just one request for addVideo. In addVideo, name should be same as video name by which it is saved. I don't know how to merge both code for this functionality. Thank you.

Upvotes: 0

Views: 1060

Answers (1)

devconcept
devconcept

Reputation: 3685

Multipart requests also support sending plain data. Just add upload.single('video') to the middleware chain like this:

router.post('/addVideo', upload.single('video'), (req,res) => {
    // do something with req.file
    var newVideo = new Video();

    newVideo._courseId = req.body.courseId;
    newVideo._chapterId = req.body.chapterId;
    newVideo.name = req.body.name;
    newVideo.des = req.body.des;

    newVideo.save((err,note) => {
        if(err){
            res.status(404).send({err: "Something went wrong"})
        } else {
            res.status(200).send({err: "Your note has been added!!"})
        }
    })
})

Now the tricky part is that on the client you should use one form to send both the file and the fields (name, des, etc). You should place all fields before your file on the form. Also this form must be multipart/form-data for the upload to work.

Upvotes: 0

Related Questions