Node JS & MongoDB File Upload
Uploading files in a Node.js application using Express and MongoDB involves several steps. This includes setting up your Express server, handling file uploads with middleware, storing files, and saving relevant data to MongoDB. Here’s a comprehensive guide on how to achieve this.
Step-by-Step Guide to File Upload with Node.js, Express, and MongoDB
1. Setting Up Your Project
First, you need to create a new Node.js project and install the required dependencies.
mkdir file-upload-example
cd file-upload-example
npm init -y
npm install express multer mongoose dotenv
- express: Web framework for Node.js.
- multer: Middleware for handling file uploads.
- mongoose: ODM for MongoDB to interact with the database.
- dotenv: Module to load environment variables.
2. Create Your Directory Structure
Create the necessary folders for your project:
mkdir uploads
touch app.js
uploads
: This directory will store the uploaded files.app.js
: The main application file.
3. Set Up Express and Middleware
In your app.js
file, set up the Express server and configure multer for file uploads.
// app.js
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads'); // Set the destination folder
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`); // Use a timestamp to avoid name collisions
}
});
const upload = multer({ storage });
// Define a simple route
app.get('/', (req, res) => {
res.send('Welcome to the File Upload API');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
4. Define the Mongoose Model
Create a model to store file information in MongoDB.
// models/File.js
const mongoose = require('mongoose');
const fileSchema = new mongoose.Schema({
filename: { type: String, required: true },
path: { type: String, required: true },
mimetype: { type: String, required: true },
size: { type: Number, required: true }
});
const File = mongoose.model('File', fileSchema);
module.exports = File;
5. Create the File Upload Route
In your app.js
, add a route to handle file uploads.
// Import the File model
const File = require('./models/File');
// File upload route
app.post('/upload', upload.single('file'), async (req, res) => {
try {
// Create a new file document in the database
const fileData = {
filename: req.file.filename,
path: req.file.path,
mimetype: req.file.mimetype,
size: req.file.size
};
const newFile = new File(fileData);
await newFile.save();
res.status(201).json({
message: 'File uploaded successfully',
file: newFile
});
} catch (error) {
res.status(500).json({ message: 'File upload failed', error });
}
});
6. Environment Variables
Create a .env
file in the root of your project to store environment variables.
MONGODB_URI=mongodb://localhost:27017/file_upload_db
Make sure MongoDB is running locally or replace the URI with your MongoDB connection string if you're using a cloud service.
7. Testing the File Upload
You can use tools like Postman or cURL to test the file upload. Here’s how to do it with Postman:
- Open Postman and create a new POST request.
- Set the URL to
http://localhost:3000/upload
. - Under the Body tab, select form-data.
- Add a key named
file
, set it to File, and choose a file to upload. - Send the request.
You should receive a response confirming that the file was uploaded successfully.
8. Accessing Uploaded Files
The uploaded files will be stored in the uploads
directory, and their metadata (like filename, path, mimetype, and size) will be saved in the MongoDB database.
Summary
This guide provides a comprehensive overview of how to handle file uploads in a Node.js application using Express and MongoDB:
- Setup: Create a Node.js project and install necessary dependencies.
- Express Server: Set up an Express server with multer for handling file uploads.
- Mongoose Model: Define a model to store file information in MongoDB.
- Upload Route: Implement a route to handle file uploads and save metadata in the database.
- Testing: Use tools like Postman to test the file upload functionality.
This setup allows you to effectively manage file uploads in your application, providing a solid foundation for further enhancements and features.