How to read the video file that I have saved in my mongodb database

1

I'm trying to save a collection inside mongodb (Lesson) where among other data this collection has a video:

Lesson Model

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var LessonSchema = Schema({

    title: String,
    creator: {type: Schema.ObjectId, ref: 'User'},
    course: {type: Schema.ObjectId, ref: 'Course'},
    video: String,
    description: String,
    created_at: String

 });

 module.exports = mongoose.model('Lesson', LessonSchema);

The next step would be to save that collection in database, this is the way I have done it:

LessonController

function saveLesson(req, res){

var params = req.body;
var lesson = new Lesson();

if (params.title && params.description && params.course) {

    lesson.title = params.title;
    lesson.creator = req.user.sub;
    lesson.course = params.course;
    lesson.video = null;
    lesson.description = params.description;
    lesson.created_at = moment().unix();

    Lesson.find({ $or: [{title: lesson.title}, {description: lesson.description}] }).exec((err, lessons) =>{

        if(err) return res.status(500).send({message: 'Petition failed'});

        if (lessons && lessons.length >=1) {

            return res.status(500).send({message: 'The lesson already exist'});

        }else{

            lesson.save((err, lessonStored) =>{

                if(err) return res.status(500).send({message: 'Petition failed'});

                if(!lessonStored) return res.status(404).send({message: 'The lesson can't be save'});

                return res.status(200).send({ lesson: lessonStored});
            });            
        }
    });

}else {
    return res.status(500).send({message: 'Please complete the require   fields'});
  }
}

Once I save the lesson in database, what I try to do is update it by uploading a video file, as you can see in the following code, where everything goes well here:

Upload the video of the lesson

function uploadVideo(req, res){

var lessonId = req.params.id;
if (req.files) {

    var file_path = req.files.video.path;
    var file_split = file_path.split('\');
    var file_name = file_split[3];
    var ext_split = file_name.split('\.');
    var file_ext = ext_split[1];

    Lesson.findById(lessonId, (err, lesson)=>{

        if (err) return res.status(500).send({message: 'Petition failed!'});

        if (!lesson) return res.status(404).send({message: 'There is not lesson to update'});

        if (lesson.creator._id != req.user.sub) {
            return removeFileOfLoad(res, file_path, 'Sorry, you don't have permition to update the data of the current lesson');
        }else{

            if (file_ext == 'avi' || file_ext == 'mp4' || file_ext == 'mkv' || file_ext == 'mpg') {

                Lesson.findByIdAndUpdate(lessonId, {video: file_name}, {new: true}, (err, lessonUpdated) =>{

                    if (err) return res.status(500).send({message: 'Petition failed'});

                    if (!lessonUpdated) return res.status(404).send({message: 'The current lesson can not be update'});

                    return res.status(200).send({lesson: lessonUpdated});
                });
            }else{
                return removeFileOfLoad(res, file_path, 'The extention is not valid!');
            }
        }
    });
}else{

    return res.status(200).send({message: 'Please select a video for the current lesson'});
   }
}

function removeFileOfLoad(res, file_path, message) {

  fs.unlink(file_path, (err)=>{
      return res.status(200).send({message: message});
  }); 
}

Everything previously implemented goes well until I try to get the video file to read it in the browser in the following way

Get video lesson by file_path

function getVideoFile(req, res){

var video_file = req.params.videoFile;
var file_path = './uploads/lessons/videos/'+video_file;

fs.exists(file_path, (exists) => {

    if (exists) {
        res.sendFile(path.resolve(file_path));
        // var rs = fs.createReadStream(file_path);
        // res.rs;
    }else{
        res.status(200).send({message: 'There is not video lesson'});
      }
   });
}

Finally my problem is that I can not read the video as I would like to do it, give it play, pause in order to read the video. I tried as I did with the lines that are commented in the code to get the video by the file_path, but it does not work ... Someone could tell me if there is a better solution to implement this functionality than the one I tried to expose them here? Greetings and thanks ... in advance.

    
asked by Aryan Garcia 26.11.2018 в 21:20
source

1 answer

0

In node the request and the response are streams, a Readable and a Writable respectively. You can do a Readable with your file and make pipe in your response. The solution is as complicated as this

const readStream = fs.createReadStream('./path/to/my/file');
readStream.pipe(res);

It would stay like this

function getVideoFile(req, res){
    const video_file = req.params.videoFile;
    const file_path = './uploads/lessons/videos/'+video_file;

    try {
        const readStream = fs.createReadStream(file_path);
        readStream.pipe(res);
    } catch(e) {
        res.status(200).send({message: 'There is not video lesson'});
    }
}

The good thing about using streams is that they make optimal use of memory. The streams use small buffers to send the information as it is read having only in memory the piece that is currently being read.

You should consider using status codes for when there is no video, using a 404 tells the front-end that the video was not found.

    
answered by 26.11.2018 / 22:05
source