Image Upload in Node JS, MongoDB Using Multer, Cloudinary
In this article, we are going to learn how to upload, update and delete images in Cloudinary and how to record its records in MongoDB.
Install node js.
Please refer to this link for details. Installing Node.js via package manager
Install the required dependencies
we need to initialize npm. When doing this the package.json file is created.
For that open terminal and run this code
npm init
After running this code the package.json file will look like this.
{"name": "cloudinary-image-upload","version": "1.0.0","description": "node js image upload using cloudinary multer mongodb","main": "server.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "AT Dilakshan","license": "ISC"}
We need a few dependencies for this lesson.
The dependencies that we require are listed below.
Express: Fast, unopinionated, minimalist web framework for node. More Details.
Mongoose: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. More Details.
Multer: Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. More Details.
Cloudinary: The Cloudinary Node SDK allows you to quickly and easily integrate your application with Cloudinary. Effortlessly optimize, transform, upload and manage your cloud’s assets. More Details.
Dotenv: Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology. More Details.
We need to run this code to install the required dependencies.
npm install express mongoose multer cloudinary dotenv
We can install the nodemon developer dependency so that the server does not stop even after the changes we make.
nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected. More Details.
Run this code to install it.
npm install -g nodemon
Now add it to the script in package.json.
"server": "nodemon server"
Now our package.json file will look like this.
{"name": "cloudinary-image-upload","version": "1.0.0","description": "node js image upload using cloudinary multer mongodb","main": "server.js","scripts": {"server": "nodemon server"},"author": "AT Dilakshan","license": "ISC","dependencies": {"cloudinary": "^1.30.1","dotenv": "^16.0.1","express": "^4.18.1","mongoose": "^6.5.2","multer": "^1.4.5-lts.1"}}
Next, let’s now create our folder structure.
Folder Structure
Create the server
We’ll build a server with the name server.js.
const express = require("express");const mongoose = require("mongoose");const app = express();const port = 3000;app.listen(port, () => {console.log(`listening on port ${port}`)});
Next, let’s connect MongoDB.
We must keep the MongoDB connection string a secret while pushing our work to GitHub or the cloud.
For that, if we store the MongoDB connection string in .env then our MongoDB connection string will be secret.
We’ll create a .env file and store the MongoDB connection string.
MONGO_CONNECTION_STRING = mongodb://localhost:27017/cloudinary
Now let’s add it to the server. js
const express = require("express");const mongoose = require("mongoose");const dotenv = require("dotenv");const app = express();dotenv.config();// Connect Databasemongoose.connect(process.env.MONGO_CONNECTION_STRING).then((result) => {console.log("mongodb connected");}).catch((err) => {console.log(err);});const port = 3000;app.listen(port, () => {console.log(`listening on port ${port}`)});const app = express();const port = 3000;app.listen(port, () => {console.log(`listening on port ${port}`)});
Create the Schema For Database Collection
To create the MongoDB Collection, we need to create the required fields in imageSchema.js.
const mongoose = require("mongoose");const collectionName = "image"; // collection Name image is pluralized(images)const imageSchema = new mongoose.Schema({title: {type: 'string',},img: {public_id: {type: 'string',},secure_url: {type: 'string',}},});module.exports = mongoose.model(collectionName, userSchema);
Setup Cloudinary File
First, we need to create a cloudinary account.
Goto Cloudinary website and register/ login. You will be redirected to your Dashboard where under Account Details you will find your Cloud Name, API Key and API Secret. Copy their values and inside the .env file create 3 variables to store those values.
Create the CRUDs
Let’s write the cruds in the imageController.js file.