A Nodejs App To Save Videos To Mongodb
Tags: webdev, node, mongodb, backenddevelopment
Published: 2024-02-10 04:20:31

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9kdok3t7c3u8qig2f4n.gif)

## Prerequisites

Before starting, make sure you have the following installed:

- Node.js: You can download and install Node.js from [here](https://nodejs.org/).

- MongoDB: Install MongoDB from [here](https://www.mongodb.com/try/download/community).

- Cloudinary Account: Sign up for a Cloudinary account at [https://cloudinary.com/](https://cloudinary.com/) and get your API key, API secret, and cloud name.

## Project Setup

1. **Create a new Node.js project:**

    ```bash
    mkdir video-uploader
    cd video-uploader
    npm init -y
    ```

2. **Install required packages:**

    ```bash
    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
```javascript
// 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();
```

## Next up, our database and don't forget we are using Mongoose
```javascript
// 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');
});
```

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1t4u8fddpyqxjmke6nw.png)

> now we add this to our code
```javascript
// 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
```javascript
// Configure Multer for video upload
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
```
## Calm Down 😁😁😁 We're almost there

![Calm Down](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e86t5qfjqp02azdk6t98.gif)

## Now that you are calm 😂, we need to create our VIDEO SCHEMA
```javascript
// Define Video model
const Video = mongoose.model('Video', {
  title: String,
  videoUrl: String,
});
```
## Now for the main application logic to be held in a post route
```javascript
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' });
  }
});
```
## lastly we must not forget to listen to our server
```javascript
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
```
> **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.

> **Do not Forget To Configure MongoDB:**

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

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
    ```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0d47b0flrs1go7gx4pdj.png)

## and my database looks like this

![DB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6ufd0xy5x0p3fiymp3h.png)

CONGRATULATIONS!!!

![YAY](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eo8j2x9m0pkivv51rfsl.gif)
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](https://github.com/FredAbod/Video-Upload) if you prefer to clone the code. And don't forget to give me a like and a star🤩😘🤩