JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads -

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    let type = req.params.type;
    let path = `./data/${type}`;
    fs.mkdirsSync(path);
    callback(null, path);
  },
  filename: (req, file, cb) => {
    const ext = mime.extension(file.mimetype);
    const random = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
    cb(null, `${Date.now()}-${random}.${ext}`);
  },
});

Here is how the router is configured -

router.post("/", auth, multer({ storage }).fields([{ name: 'image', maxCount: 1 }, { name: 'video', maxCount: 1 }]), addMovie); 
When I log console.log(req.files), this is what I see:

[Object: null prototype] {
  image: [
    {
      fieldname: 'image',
      originalname: ' .png',
      encoding: '7bit',
      mimetype: 'image/png',
      destination: './data/undefined',
      filename: '1631293039713-7613.png',
      path: 'data\\undefined\\1631293039713-7613.png',
      size: 13133
    }
  ],
  video: [
    {
      fieldname: 'video',
      originalname: 'file_example_MP4_480_1_5MG.mp4',
      encoding: '7bit',
      mimetype: 'video/mp4',
      destination: './data/undefined',
      filename: '1631293039720-3601.mp4',
      path: 'data\\undefined\\1631293039720-3601.mp4',
      size: 1570024
    }
  ]
}

I have both an image and a video being uploaded. Now, I want to access the properties within these objects but I'm not sure how.

After trying req.files.image[0], here is the error message I received -

Property 'image' does not exist on type '{ [fieldname: string]: File[]; } | File[]'. Property 'image' does not exist on type 'File[]'.ts(2339)

Answer №1

One approach to consider is accessing the first image file using (req as any).files.image[0]. Unfortunately, dealing with typings for the req object can be a bit cumbersome.

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

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...

Having trouble with my initialData in react-query - any suggestions on how to fix it?

I encountered an issue while trying to implement code using initialData in React Query. The output does not display as expected, and the key is not visible in the react-query-dev-tool. View image here import { useQuery, useQueryClient } from 'react-qu ...

Using node-native to authenticate in MongoDB is a surefire way to ensure the

I'm currently facing an issue while attempting to save a document in MongoDB within my Nodejitsu/MongoHQ application. Everything works perfectly locally, but the MongoHQ database requires authentication and it fails even with the correct user/password ...

ERROR TypeError: Unable to access the 'nativeElement' property since it is undefined in Angular 5

I have encountered a problem while working on my application. Although similar issues have been asked before, I believe mine is slightly different. In my application, when a user deletes products from their cart, I want to automatically close the modal wi ...

Pass an array containing an HTML string to the $.post method in jQuery

I have a problem with displaying HTML content fetched from a PHP script using the jQuery $.post method: $.post('{$site_url}tests/tests/content', params, function (data) { $('#some-div1').html(data[1]); $('#some-div2').htm ...

Output PHP code within the HTML content using javascript's innerHTML functionality

I wrote a PHP function that increments by +1 every time it is executed. function count_likes(){ $collect=file_get_contents('like_counter.txt')+1; $count=file_put_contents("like_counter.txt", $collect); echo $collect; I also have a JavaScr ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

In TypeScript, combining the numbers 0 and 1 results in the value 01

I am in the process of developing a Shopping Card feature. private _card: Map<Product, number> = new Map<Product, number>(); ... addToCard(prod: Product, amount: number = 1): void { const totalAmount: number = this._card.get(prod) + amou ...

How come a null variable continues to widen to type any even when strictNullChecks is enabled?

According to the TypeScript Documentation, if strictNullChecks is true, there should be no type widening. Also, the typeof nul should be null. let nul = null; // typeof nul = any let undef = undefined; // typeof undef = any Check it out in the Playground ...

What is the process for sharing your website content on Google Blogger?

I am currently developing a dashboard for a small business website and I would like to implement a feature that allows users to post directly to their Blogger blog from the dashboard of their own website. This eliminates the hassle of having to switch betw ...

blurring out of an input field and a division element

I am currently working on creating a dropdown suggestion box that hides when the input field and dropdown box are no longer in focus. My HTML code: <input type="text" id="user_address"> <div id="user_address_sg">SUGGESTION</div> <di ...

Vue should only activate the element that has been clicked on

I'm currently working on my first Vue project and encountering an issue with triggering a child component within a table cell. Whenever I double click a cell, the `updated` event is being triggered in all child components associated with the table cel ...

Using Typescript to change a JSON array of objects into a string array

I'm currently working with the latest version of Angular 2. My goal is to take a JSON array like this: jsonObject = [ {"name": "Bill Gates"}, {"name": "Max Payne"}, {"name": "Trump"}, {"name": "Obama"} ]; and convert it into a st ...

How to retrieve HTML attribute using D3 techniques

Looking to iterate through all rect nodes in the code snippet below: d3.selectAll("svg g rect") .on('mouseover', function (d) { console.log(this); }); When Console.log is executed, the following is printed: <rect class="cls" na ...

Understanding the implementation of options within dataTables that have been initialized with an aaData JavaScript array

When initializing my datatable, I used an aaData object and specific options like so: $('#dataTable').dataTable(dataTableObj, { "bPaginate": false, "bLengthChange": false, "bFilter": true, "bSort": false, "bInfo": false, ...

Keep retrying a request until a valid response is received

I am working with an API that requests data from a backend service. Sometimes, the data may not be available at the time of the initial request. In such cases, I need the system to retry up to 5 times until the data is present. I can confirm that the dat ...

Welcome Message using Discord.js V13

As a newcomer to bot creation, I am facing an issue with my welcome message in discord.js v13. Previously working in v12, I am now encountering difficulties sending a message to a specific channel when a user joins the server. After some investigation, I r ...

Exploring the concept of front-end deletion through ajax technology

I'm currently tackling a front-end CRUD RESTful API project and encountering challenges specifically related to the DELETE and PUT methods. While I have successfully managed to implement the GET and POST functionalities, utilizing a forms.html file f ...