Not getting the right response from insomnia while uploading the file

52 Views Asked by At

Hey guys so i m trying to create a file sharing system using nodejs, mongodb and insomnia. so far i have managed to get to the uploading file part. insomnia is uploading the file to my upload folder in the code but its not uploading it to the mongodb server. at first i thought the server was not connected but after checking the server is connected, i m just trying to figure out what the error is and what i can do to fix it. this process isnt hampering me moving forward with the project in a way as i can continue writing the code for the download page, however if it doesnt upload to the server, i wont be able to generate a download link

server.js code block

require('dotenv').config();
const express = require('express');
const app = express();
const connectDB = require('./config/db');
connectDB();


const PORT = process.env.PORT || 8000;

//initialize routes
app.use('/api/files', require('./routes/files'));
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

file.js codeblock

const router = require('express').Router();
const multer = require('multer');
const path = require('path');
const File = require('../models/file');
const {v4: uuidv4} = require('uuid');
let store = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1E9)}${path.extname(file.originalname)}`;
        cb(null, uniqueName);
    }
});

let upload = multer({
    storage: store,
    limits: {
        fileSize: 1024 * 1024 * 5
    }
}).single('myfile');

router.post('/', (req, res) => {
    
    //store file in upload folder
    
    upload(req, res, async(err) => {
        //validation of the request
        if (!req.files) {
            return res.json({errors: 'All files are required'});
        }
        //storing the data in the database
        const file = new File({
            filename: req.file.filename,
            path: req.file.path,
            size: req.file.size,
            uuid: uuidv4(),
        });
        const response = await file.save();
        return res.json({file: `${process.env.BASE_URL}/files/${response.uuidv4}`});
    });
});

module.exports = router;

.env block

MONGODB_URI = "mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority"
BASE_URL = "http://localhost:8000"

file.js model block

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const fileSchema = new Schema({
    filename: {type: String, required: true},
    path: {type: String, required: true},
    size: {type: Number, required: true},
    uuid: {type: String, required: true},
    sender: {type: String, required: false},
    reciever: {type: String, required: false},
}, {timestamps: true});


module.exports = mongoose.model('File', fileSchema);
0

There are 0 best solutions below