A Nodejs App To Save Videos To Mongodb

fredabod

FredAbod

Posted on February 10, 2024

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;


## Next up, we'll add our middleware
```javascript
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,
  });

Next up, we configure multer

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

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🀩😘🀩

πŸ’– πŸ’ͺ πŸ™… 🚩
fredabod
FredAbod

Posted on February 10, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

A Nodejs App To Save Videos To Mongodb