DEV Community

FredAbod
FredAbod

Posted on

11

A Nodejs App To Save Videos To Mongodb

Setting Up a Node.js App to Save Videos to MongoDB with Multer and Cloudinary

In this tutorial, I'll walk you through the process of setting up a Node.js application to upload videos, save them to MongoDB, and store the video URLs in Cloudinary. We'll be using the Multer library for handling file uploads and the Cloudinary service for storing and managing our video files.

You don't Have to worry this article is going to use the simplest logics and it would be step by stepπŸ˜‰πŸ˜‰πŸ˜‰

Do Not Worry

Prerequisites

Before starting, make sure you have the following installed:

  • Node.js: You can download and install Node.js from here.

  • MongoDB: Install MongoDB from here.

  • Cloudinary Account: Sign up for a Cloudinary account at https://cloudinary.com/ and get your API key, API secret, and cloud name.

Project Setup

  1. Create a new Node.js project:

    mkdir video-uploader
    cd video-uploader
    npm init -y
    
  2. Install required packages:

    npm install express mongoose multer cloudinary
    
  3. Create a new file app.js and open it in your favorite text editor.

    Firstly let's import our packages

// app.js

const express = require('express');
const mongoose = require('mongoose');
const dotenv = require("dotenv");
const multer = require('multer');
const cloudinary = require('cloudinary').v2;
Enter fullscreen mode Exit fullscreen mode

Next up, we'll add our middleware

const app = express();
const port = 3000;
dotenv.config();
Enter fullscreen mode Exit fullscreen mode

Next up, our database and don't forget we are using Mongoose

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/videos');
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});
Enter fullscreen mode Exit fullscreen mode

Now we configure our Cloudinary credentials, you get these from your Cloudinary account. I hid mine with the dotenv package

Your Cloudinary profile should look like this

Cloudinary

now we add this to our code

// Configure Cloudinary
cloudinary.config({
    cloud_name: process.env.CLOUDINARY_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
  });
Enter fullscreen mode Exit fullscreen mode

Next up, we configure multer

// Configure Multer for video upload
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
Enter fullscreen mode Exit fullscreen mode

Calm Down 😁😁😁 We're almost there

Calm Down

Now that you are calm πŸ˜‚, we need to create our VIDEO SCHEMA

// Define Video model
const Video = mongoose.model('Video', {
  title: String,
  videoUrl: String,
});
Enter fullscreen mode Exit fullscreen mode

Now for the main application logic to be held in a post route

app.post('/upload', upload.single('video'), async (req, res) => {
  try {
    // Check if req.file is defined
    if (!req.file || !req.file.buffer) {
      return res.status(400).json({ error: 'No file provided in the request' });
    }

    // Upload video to Cloudinary
    const result = await cloudinary.uploader.upload_stream({ resource_type: 'video' }, async (error, result) => {
      if (error) {
        console.error('Error uploading to Cloudinary:', error);
        return res.status(500).json({ error: 'Error uploading to Cloudinary' });
      }

      // Save video details to MongoDB with Cloudinary URL
      const video = new Video({
        title: req.body.title || 'Untitled Video',
        videoUrl: result.secure_url,
      });

      await video.save();

      res.status(201).json({ message: 'Video uploaded successfully'});
    }).end(req.file.buffer);
  } catch (error) {
    console.error('Error uploading video:', error);
    res.status(500).json({ error: 'Error uploading video' });
  }
});
Enter fullscreen mode Exit fullscreen mode

lastly we must not forget to listen to our server

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Do not forget to Configure your Cloudinary credentials:

Replace `process.env.CLOUDINARY_NAME`, `process.env.CLOUDINARY_API_KEY`, and `process.env.CLOUDINARY_API_SECRET` with your Cloudinary credentials in the `cloudinary.config` section.
Enter fullscreen mode Exit fullscreen mode

Do not Forget To Configure MongoDB:

In `app.js`, replace `'mongodb://localhost:27017/videos'` with your MongoDB connection string.
Enter fullscreen mode Exit fullscreen mode

Let's break down the main components of the code a bit:

  • The Video Upload Route: We created a route http://localhost:3000/upload that handles video uploads. It uses Multer to handle file uploads, Cloudinary to upload videos, and Mongoose to save video details to MongoDB.

Run the Application

Run your Node.js application:

```bash
node app.js
```
Enter fullscreen mode Exit fullscreen mode

Your application should now be running on http://localhost:3000.

Test the Video Upload

Send a POST request to http://localhost:3000/upload with a video file attached. Make sure to include the title field in the request body.

I use Postman to test it looks like this

Postman

and my database looks like this

DB

CONGRATULATIONS!!!

YAY
You have successfully set up a Node.js application to save videos to MongoDB using Multer for file uploads and Cloudinary for storage. You can now integrate this code into your existing projects or expand upon it for more advanced use cases.

Here's a link to my github repo if you prefer to clone the code. And don't forget to give me a like and a star🀩😘🀩

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (1)

Collapse
 
ali_raza_b8630de93e258819 profile image
Ali Raza β€’

Amazing well explained

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay