Reputation: 65
this my code, which works fine while uploading image but whenever I am going to upload video/files which is more than 16mb , its failed to upload , so what to do , please help , i am a beginner ! I am using formidable as a middleware , lodash and fs , But don't know to do next
const Freecoursevideo = require("../models/freecoursevideo");
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
exports.createFreecoursevideo = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, file) => {
if (err) {
return res.status(400).json({
error: "problem with image",
});
}
//destructure the fields
const { name, description } = fields;
if (!name || !description) {
return res.status(400).json({
error: "Please include all fields",
});
}
let freecoursevideo = new Freecoursevideo(fields);
console.log(freecoursevideo);
//handle file here
if (file.video) {
if (file.video.size > 1000000000000000000000) {
return res.status(400).json({
error: "File size too big!",
});
}
freecoursevideo.video.data = fs.readFileSync(file.video.path);
freecoursevideo.video.contentType = file.video.type;
}
// console.log(freecoursevideo);
//save to the DB
freecoursevideo.save((err, freecoursevideo) => {
if (err) {
res.status(400).json({
error: "Saving Freecoursevideo in DB failed",
});
}
res.json(freecoursevideo);
});
});
};
Upvotes: 0
Views: 310
Reputation: 1625
Mongodb has a limit of 16MB on the size of document which you can save to a collection.
Since you are trying to save videos of size greater than 16mb to your freecoursevideo
collection, you are getting an error.
Solution:-
You will have to Gridfs
to save documents of size greater than 16mb.
I your case i would suggest you get rid of freecoursevideo
collection and save all your videos in gridfs
whether it is more than 16mb or not. So that you don't have to query two places for getting your videos.
So how to save to gridfs?
bin
folder of your mongo database tools.Ensure that the bin
folder has following content.
Open command prompt at this location. Run the below command by replacing , , <DB_NAME> and <PATH_TO_VIDEO>
mongofiles --host=<HOST> --port=<PORT> -d=<DB_NAME> put <PATH_TO_VIDEO>
Above command will save the video in fs.files
and fs.chunks
collections. Name of these collections are predefined by mongo and cannot be changed.
Above exercise will you the understanding of how gridfs works. Then you can go ahead look for mongoose way of doing this. Adding a link to article that may help.
https://www.freecodecamp.org/news/gridfs-making-file-uploading-to-mongodb/
Upvotes: 1