How to upload files into MongoDB using grifFs Storage and Node js

uploading media files into the Monogb database is quite convenient for a beginner developer. lots of developers face problems when they want to store files in MongoDB greater than 16MB, Because MongoDB Document size is 16MB, that's why we can't upload files that are greater than 16MB into a single document. To resolve this problem, MongoDB provides a method called GridFs Bucket in which mongoDB stores files by dividing them into 255kb chunks. you can read much more about it by clicking below.
now let's set up our simple project in which we will learn how to upload files into the MongoDB database using the GridFs method.
for this, you must have installed node js in your local system, if not make sure you have installed it before getting further.
In this blog, we will explore how to upload files into MongoDB using the gridfs-storage package in combination with Node.js, Express, Multer, and Mongoose. GridFS is a specification for storing and retrieving large files (such as images, audio, video, etc.) in MongoDB.
Prerequisites
Before we begin, make sure you have the following tools and libraries installed:
Node.js and npm
Express.js
Mongoose
Multer
GridFS Storage
Step 1: Set Up the Project
Make a project directory, open it in any code editor and run this command into the terminal "npm init -y"
npm init -y
now after setting up your, you will be able to see a package.json file in your root directory.
now install these dependencies. by running this command.
npm install express mongoose multer gridfs-stream
Step 2: Create the Express Server
Create a file named app.js (or index.js) in your project directory and set up the basic Express server:
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
const mongoURI = 'mongodb://localhost:27017/gridfs-file-upload';
const connectToMongoDB = async ()=>{
try{
await mongoose.connect(mongoURI)
console.log('connected to database.')
}catch(error){
console.log(error)
}
}
connectToMongoDB();
app.get('/', (req, res) => {
res.json({ message: 'Welcome to GridFS File Upload!' });
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 3: Configure Multer and GridFS Storage
import multer from 'multer'
import { GridFsStorage } from 'multer-gridfs-storage'
export const upload = multer({
storage: new GridFsStorage({
url: mongoURI ,
file: (req, file) => {
return {
bucketName: "media",
filename: `${Date.now()}.${file.originalname.split('.').pop()}`
}
}
})
})
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded' });
}
return res.json({ message: 'File uploaded successfully' });
});
Step 4: Run the Application
Start the Express server:
node app.js
by hitting the upload route with post API along with a file in the form of FornData you'll be able to upload the file into the MongoDB database, This setup allows you to upload files to MongoDB using the GridFS specification. You can further enhance this application by adding features such as file retrieval, deleting files, and more.
Feel free to explore more advanced features and customize the application according to your needs.
if you want to know how can we upload files without using 'multer-gridfs-storage', comments down and ill be wring the blog on that too. similarly, if you want to know how can we retrieve files from the GridFs Bucket, let me know in the comments.



