Is there a way to upload a video, file, and PDF to a database using multer?

There is a database schema defined in the code below:

const mongoose = require("mongoose");
const FormCourse_schema = new mongoose.Schema({
  FormCourse: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "cards",
    required: true,
  },
  date: { type: String },
  file: { type: String },
  video: { type: String },
  pdf: { type: String },
});
module.exports = mongoose.model("FormCourse", FormCourse_schema);

The controller function for posting data is shown below:

exports.post_FormCourse = async (req, res, next) => {
  try {
    // if (!req.userId) return res.status(406).json({ message: "Unauthenticated" });

    const FormCourse_id = req.body.FormCourse_id;
    const isFormCourse = FormCourse.findById(FormCourse_id);
    if (isFormCourse.length < 1) res.status(202).json("FormCourse not found");
    const course = new FormCourse({
      date: req.body.date,
      file: req.file.path,
      video: req.file.path,
      pdf: req.file.path,
    });
    const result = await course.save();
    res.status(200).send({
      result: result,
      request: {
        type: "GET",
        url: "localhost:3002/form/" + result._id,
      },
    });
  } catch (error) {
    res.status(404).json({ message: "invalid id", error: err });
  }
};

A router is defined below with endpoints for POST, PATCH, and DELETE:

const express = require("express");
const router = express.Router();
const FormCourses = require("../controllers/formCourses");
const checkAuth = require("../middleware/checkAuth");
const multer = require("multer");

// Multer configurations for different file types

// Endpoint definitions

module.exports = router;

The main app file includes error handling for 500 errors:

const express = require("express");
const app = express();
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");

// Middleware and router configurations

// Handling errors

module.exports = app;

This code has a testing scenario for a 500 error with Postman: There might be an error due to multiple fields for uploading in the router.post method. How can this be resolved?

Answer №1

I had some difficulty grasping the concept of your project, which is why I couldn't integrate the code into it.

However, I believe this solution might be beneficial to you. It is a form that enables the uploading of 3 files to mongo GridFS. Upon completion, you will receive the data of the uploaded files, including the ID and extension. To download the file, simply pass the ID to the /download route.

For instance: http://localhost:3008/download?id=639bd2fe44f218a5e0ea58d4

const express = require('express')
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
const { GridFsStorage } = require('multer-gridfs-storage');
const multer = require('multer'); //use version 1.4.2

const connection = mongoose.connect("mongodb+srv://ghazali:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed88888ace8f8e7fea2ea9895889792d8bee3f2f7e29df2e4e3e9e5e7adb7b4f2e1e3e2ebf1f9">[email protected]</a>/?retryWrites=true&w=majority");

const storage = new GridFsStorage({ db: connection });

const upload = multer({ storage });

let bucket;

connection.then(() => {
    bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db);
})

const app = express()

app.post('/upload', upload.array('files'), async (req, res) => {

    res.send(req.files); //req.files provides the ID and extension, enabling the file to be downloaded later
})

app.get('/', async (req, res) => {

    res.send(`
    <form action="upload" method="post" enctype="multipart/form-data">
        <label for="pdf_file">PDF: </label>
        <input id="pdf_file" type="file" accept="application/pdf" name="files">
        <br>
        <br>
        
        <label for="pdf_file">File: </label>
        <input id="pdf_file" type="file" name="files">
        <br>
        <br>
        
        <label for="pdf_file">Video: </label>
        <input id="pdf_file" type="file" accept="video/*" name="files">
        <br>
        <br>
        <input type="submit">
    </form>
  `);
});

app.get("/download", (req, res) => {
    res.attachment("download"); //the saved extension is used here
    bucket.openDownloadStream(mongoose.Types.ObjectId(req.query.id)).pipe(res); //the ID is passed through the query string, but there are alternative methods
})


app.listen(3008, () => {
    console.log("Listening on port 3008");
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Array of generic types in Typescript

Here's a method that I have: getFiveObjectsFromArray(array: T[]) { return array.slice(0, 5); } I've been using this method multiple times. Is there a way in TypeScript to pass a generic argument instead of using multiple types? Also, when ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs. import * as strings from './strings'; const generateUuidSpy = jest.spyOn(st ...

Obtain the URL from a Span Class located within a table

As I embark on my journey to learn javascript and jQuery, it's clear that my knowledge is quite rudimentary at this point. An attempt to make edits to a script written in Tampermonkey by a friend has led me down a path of extensive Googling with littl ...

Dealing with unprocessed promise rejection in an express application

I currently have a Node Express Application and I am looking to enhance the error handling process. Below is how my route endpoint is defined: app.get('/example/getActiveId', async (req, res, next) => { // Code for fetching details and valid ...

Having trouble toggling between the trending and search features on giphy website

I've been developing a chat application with NextJS and I'm currently working on integrating GIPHY images into it. Although I have the basic setup in place, I'm facing issues when switching between the giphy.search() and giphy.trending() fu ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

Decipher encoded parameters utilizing the JavaScript encodeURIComponent method

I'm dealing with an issue in my application where text entered by a user is sent to the server as part of a URL to render an image. The text is encoded using the encodeURIComponent function, but I'm running into problems with certain characters l ...

Enhancing Node.js Using EJS Helper Functions

Can you set up helper functions in EJS templates that can be accessed from any EJS template? Here's how it could potentially work: app.js ejs.helpers.greetUser = function(name) { return 'Welcome, ' + name; }); index.ejs <%= greetU ...

Adding text to an existing div element using jQuery and ensuring the div tag automatically adjusts its height according to the text length

I have attempted to implement the following code, but unfortunately, it is not functioning as expected. I am hopeful that someone can assist me. I am seeking a way for the div tag to dynamically increase its height based on the size of the text. Does any ...

Navigating through events within React

I'm working on creating a login page, where upon clicking the submit button it should navigate to the Dashboard page. However, I seem to be encountering an issue with my code. After entering login details and clicking on the login button, the details ...

What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel. Incorporating Google APIs dependencies required me to obtain a Cli ...

What is the reason behind having to refresh my ReactJS page despite it being built with ReactJS?

I have developed a task management application where users can input notes that should automatically update the list below. However, I am facing an issue where the main home page does not display the updated todos from the database unless I manually refres ...

Tips for creating a hover-activated dropdown menu

How can I create a drop-down menu in my horizontal navigation bar that appears when hovering over the Columns tab? The drop-down menu should include options such as Articles, Videos, Interview, and Fashion. To better illustrate what I am looking for, here ...

Library for HTML styling in JavaScript

Is there a reliable JavaScript library that can automatically format an HTML code string? I have a string variable containing unformatted HTML and I'm looking for a simple solution to beautify it with just one function call. I checked npmjs.com but co ...

Verify the Javascript for file upload in ASP.NET folder prior to uploading it

Struggling with this problem for days now, I could really use some fresh perspective. My setup includes Windows Server 2012, IIS 8.0, and ASP.NET 4.5. I'm new to both IIS and ASP.NET, so please bear with me. The website I'm working on involves f ...

Do not trigger mouseleave events when absolute positioned elements have overlapping layers

I am facing a challenge with a table that includes multiple rows that need to be editable and deletable. To achieve this, I have created a <div> containing buttons that should appear when hovering over the rows. While this setup works well, I am enco ...

The conversion from CSV to JSON using the parse function results in an inaccurate

I am having trouble converting a CSV file to JSON format. Even though I try to convert it, the resulting JSON is not valid. Here is an example of my CSV data: "timestamp","firstName","lastName","range","sName","location" "2019/03/08 12:53:47 pm GMT-4","H ...

Creating GeoJson using JavaScript

Currently, I am retrieving a latitude/longitude array using Ajax $.ajax({ type: "POST", url: '../m/m_share.php', data: 'zone=' + zone, dataType: 'json', success: function(tab) { var i = 0; ...

Javascript is unable to access the occupied value. Error: Unable to read property 'weight' of undefined

I encountered a strange issue that I wasn't expecting. The snippet of code below represents a simple function. However, the problem arises when I try to access 'truckArray[0].weight' and receive an error stating TypeError: Cannot read prop ...