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πππ
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
-
Create a new Node.js project:
mkdir video-uploader cd video-uploader npm init -y
-
Install required packages:
npm install express mongoose multer cloudinary
-
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();
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');
});
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
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
Now that you are calm π, we need to create our VIDEO SCHEMA
// 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
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
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
and my database looks like this
CONGRATULATIONS!!!
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.
Top comments (1)
Amazing well explained