title: How to insert and retrieve video from mongodb in node js
body: <p>I new to mean stack. I want to upload video to mongodb and then I want to retrieve it.</p>
  
  <blockquote>
    <p>this is app.js file</p>
  </blockquote>
  
  <pre><code>  `const express = require('express');
  const bodyParser = require('body-parser');
  const path = require('path');
  const crypto = require('crypto');
  const mongoose = require('mongoose');
  const multer = require('multer');
  const GridFsStorage = require('multer-gridfs-storage');
  const Grid = require('gridfs-stream');
  const methodOverride = require('method-override');
  
  const app = express();
  
  // Middleware
  app.use(bodyParser.json());
  app.use(methodOverride('_method'));
  app.set('view engine', 'ejs');
  
  // Mongo URI
  const mongoURI = 'mongodb://fawad:Fawad123@ds155243.mlab.com:55243/imageupload';
  
  // Create mongo connection
  const conn = mongoose.createConnection(mongoURI);
  
  // Init gfs
  let gfs;
  
  conn.once('open', () =&gt; {
    // Init stream
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('uploads');
  });
  
  // Create storage engine
  const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) =&gt; {
      return new Promise((resolve, reject) =&gt; {
        crypto.randomBytes(16, (err, buf) =&gt; {
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex') + path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'uploads'
          };
          resolve(fileInfo);
        });
      });
    }
  });
  const upload = multer({ storage });
  
  // @route GET /
  // @desc Loads form
  app.get('/', (req, res) =&gt; {
    gfs.files.find().toArray((err, files) =&gt; {
      // Check if files
      if (!files || files.length === 0) {
        res.render('index', { files: false });
      } else {
        files.map(file =&gt; {
          if (
            file.contentType === 'video/mp4' ||
            file.contentType === 'video/webm '
          ) {
            file.isVideo = true;
          } else {
            file.isVideo = false;
          }
        });
        res.render('index', { files: files });
      }
    });
  });
  
  // @route POST /upload
  // @desc  Uploads file to DB
  app.post('/upload', upload.single('file'), (req, res) =&gt; {
    // res.json({ file: req.file });
    res.redirect('/');
  });
  
  // @route GET /files
  // @desc  Display all files in JSON
  app.get('/files', (req, res) =&gt; {
    gfs.files.find().toArray((err, files) =&gt; {
      // Check if files
      if (!files || files.length === 0) {
        return res.status(404).json({
          err: 'No files exist'
        });
      }
  
      // Files exist
      return res.json(files);
    });
  });
  
  // @route GET /files/:filename
  // @desc  Display single file object
  app.get('/files/:filename', (req, res) =&gt; {
    gfs.files.findOne({ filename: req.params.filename }, (err, file) =&gt; {
      // Check if file
      if (!file || file.length === 0) {
        return res.status(404).json({
          err: 'No file exists'
        });
      }
      // File exists
      return res.json(file);
    });
  });
  
  // @route GET /image/:filename
  // @desc Display Image
  app.get('/video/:filename', (req, res) =&gt; {
    gfs.files.findOne({ filename: req.params.filename }, (err, file) =&gt; {
      // Check if file
      if (!file || file.length === 0) {
        return res.status(404).json({
          err: 'No file exists'
        });
      }
  
      // Check if image
      if (file.contentType === 'video/mp4' || file.contentType === 'video/webm') {
        // Read output to browser
        const readstream = gfs.createReadStream(file.filename);
        readstream.pipe(res);
      } else {
        res.status(404).json({
          err: 'Not an image'
        });
      }
    });
  });
  
  // @route DELETE /files/:id
  // @desc  Delete file
  app.delete('/files/:id', (req, res) =&gt; {
    gfs.remove({ _id: req.params.id, root: 'uploads' }, (err, gridStore) =&gt; {
      if (err) {
        return res.status(404).json({ err: err });
      }
  
      res.redirect('/');
    });
  });
  
  const port = 9000;
  
  app.listen(port, () =&gt; console.log(`Server started on port ${port}`));
  `
  </code></pre>
  
  <blockquote>
    <p>index.ejs</p>
  </blockquote>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  
  &lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt;
    &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"&gt;
    &lt;style&gt;
      video {
        width: 100%;
      }
    &lt;/style&gt;
    &lt;title&gt;Mongo File Uploads&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
    &lt;div class="container"&gt;
      &lt;div class="row"&gt;
        &lt;div class="col-md-6 m-auto"&gt;
          &lt;h1 class="text-center display-4 my-4"&gt;Mongo File Uploads&lt;/h1&gt;
          &lt;form action="/upload" method="POST" enctype="multipart/form-data"&gt;
            &lt;div class="custom-file mb-3"&gt;
              &lt;input type="file" name="file" id="file" class="custom-file-input"&gt;
              &lt;label for="file" class="custom-file-label"&gt;Choose File&lt;/label&gt;
            &lt;/div&gt;
            &lt;input type="submit" value="Submit" class="btn btn-primary btn-block"&gt;
          &lt;/form&gt;
          &lt;hr&gt;
          &lt;% if(files){ %&gt;
            &lt;% files.forEach(function(file) { %&gt;
              &lt;div class="card card-body mb-3"&gt;
                &lt;% if(file.isVideo) { %&gt;
                  &lt;video src="video/&lt;%= file.filename %&gt;" alt=""&gt;
                  &lt;% } else { %&gt;
                    &lt;%= file.filename %&gt;
                      &lt;% } %&gt;
                        &lt;form method="POST" action="/files/&lt;%= file._id %&gt;?_method=DELETE"&gt;
                          &lt;button class="btn btn-danger btn-block mt-4"&gt;Delete&lt;/button&gt;
                        &lt;/form&gt;
              &lt;/div&gt;
              &lt;% }) %&gt;
                &lt;% } else { %&gt;
                  &lt;p&gt;No files to show&lt;/p&gt;
                  &lt;% } %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  
    &lt;script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
      crossorigin="anonymous"&gt;&lt;/script&gt;
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
      crossorigin="anonymous"&gt;&lt;/script&gt;
    &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
      crossorigin="anonymous"&gt;&lt;/script&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>this code work for image..when I used (file.contentType = image/png).
  but for video it's not working.. is Image and video upload are same?</p>