"Encountered an issue with undefined path when uploading a file using multer through a

My RESTapi built using express includes multer for file uploads. Creating a new item or post functions correctly. However, I am facing an issue with the put route and the function responsible for saving and updating the post/gear.

If the product image field is left empty, it results in:

Error: Cannot read property 'path' of undefined
    at /Users/Zack/Desktop/LeFIAT/lefiatV2/routes/gear.js:81:34

When all the fields in the product information are filled out, it returns a duplicate key error:

MongoServerError: E11000 duplicate key error collection: lefiatv2.products index: slug_1 dup key: { slug: "joey" }
    at /Users/Zack/Desktop/LeFIAT/lefiatV2/node_modules/mongodb/lib/operations/update.js:80:33

The object is being populated correctly, but I am struggling to find the correct path or setup for the function.

{
  fieldname: 'image',
  originalname: 'TorridV2_Toggle__.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './public/products/',
  filename: '2022-02-02T15:44:30.813ZTorridV2_Toggle__.jpg',
  path: 'public/products/2022-02-02T15:44:30.813ZTorridV2_Toggle__.jpg',
  size: 23382
}

In the edit.ejs file:

Edit Product
<form action="/gear/<%= product.slug %>?_method=PUT" method="POST" enctype="multipart/form-data">
    <%- include('../partials/product_fields')  %>
</form>

In the product_fields.ejs file:

<div class="form-group">
    <label for="title">Title</label>
    <input type="text" name="title" id="title" class="form-control" value="<%= product.title %>" required>
</div>

<div class="form-group">
    <label for="price">Price</label>
    <input type="number" min="1" step="0.01" name="price" id="price" class="form-control"
        required><%= product.price %></input>
</div>

... // Similar structure for other form fields

<a href="/gear" class="btn btn-secondary"> Cancel </a>

<button type="submit" class="btn btn-primary"> Save </button>

In the product.js modal:

...

// Rest of the unchanged code following this section

...

In the gear.js route:

...

// Rest of the unchanged code following this section

...

In the server.js file:

...

// Rest of the unchanged code following this section

...

Answer №1

When working with req.file.path, it's a good idea to use optional chaining to avoid errors. Here's how you can do it:

req.file?.path (sort of)

The error message is basically saying - "Hey, where is the path? There's no path because it's undefined." So, if you don't pass the file, your result will be:

undefined.path

Here's an example (using nestjs):

async updateCommit(
@Res() res,
@Param('user_id') user_id: string,
@Param('repo_id') repo_id: string,
@Param('commited_id') commited_id: string,
@Body() updatedCommit: UpdateCommitDto,
@UploadedFile() file: UpdateCommitDto["file"]): Promise<User> {
Object.assign(updatedCommit, {
  file: file?.path,
  createdAt: false,
  updatedAt: Date.now
})
const response = await this.commitService.updateCommit(user_id, repo_id, commited_id, updatedCommit)
return res.status(HttpStatus.OK).json({ response })}

The end result :

Before the update

After the update

Apologies for the low reputation image hosting!

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

Finding the mouseover event for an element that is beneath an overlaid div

There are four div elements, and on mouseover, the selected div will get zoomed. However, I also need to capture the mouseover event for the remaining three underlying divs, even when one is overlayed. This way, I can zoom out the previously selected div a ...

Text box content does not refresh unless the page is reloaded

My text box (tbAdresse) is initially empty. I'm using the following JavaScript code to set its value: origin = document.getElementById("tbAdresse").value; if (origin == "") origin = <%=this.GetFormatStringCoordonnees("Paris")% ...

Is there a way to concatenate arrays without using the Array.flat method?

I am encountering an issue with a specific function that I have const flat = function(arr, n) { if (n == 0) { return arr; } else if (n == 1) { let newarr = [] for (let i = 0; i < arr.length; i++) { if (Number.isInteger(arr[i])) ...

Utilizing AngularJS to incorporate a global scope function within another function

I have a specific AngularJS function named editlocation that triggers a Modal window to edit three data points. Following this process, I aim to execute plotmarkers, which is utilized in another scenario of an ng-click. Despite attempting different approa ...

My website built with the Celia template from Envato is loading slowly. It is taking longer than anticipated to load all the content

After purchasing the Celia template from Envato Element, I made several edits to the code for my website. You can view my hosted website on Github at: https://github.com/rosyhnguyen/rosyhnguyen.github.io. Additionally, I used the domain from Namecheap: Ev ...

I can't seem to figure out why my attempts to set a cookie through Express are failing

I am currently facing an issue with sending a cookie back to my React app after logging in. In my server, I have set up a test response: res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end(); In the app ...

Exploring search filters using KnockoutJS

I'm currently working on incorporating a search filter into my web application. After reading some informative articles and exploring various Jsfiddles, I've attempted to enable searching by TypeName to display the corresponding row with that spe ...

Is it possible to observe a collection of variables that are not within the current scope, but are still being utilized in Angular?

Consider the following scenario with data coming from a service: myService.var1 myService.var2 myService.var3 Typically, you would need to monitor each variable individually like this: $scope.$watch(function(){ return myService.var1 }, fun ...

Execute the second method once the first method has completed its execution

As I develop my npm package, I am faced with the challenge of ensuring that one method waits for another to complete before executing. For example: var package = require('myNpmPackage'); package.method1(options); ... Later on, possibly in a dif ...

The Proper Way to Include External CSS in a Next.js Page Without Triggering Any Warnings

I find myself in a scenario where I must dynamically inject CSS into a webpage. The content of this page is constantly changing, and I am provided with raw HTML and a link to a CSS file from a server that needs to be displayed on the page. My attempt to ...

Incorporating new functionality into the current .js file to automatically collapse the navbar when clicking outside

Previously, I utilized .js for my sticky navbar in Bootstrap 4.1.3 and it worked perfectly. However, I attempted to add a function in the script to collapse the navbar on mobile devices when clicking outside the menu, but it wasn't successful. Here i ...

Unable to display content on page when using node.js and express

I have organized my controllers in the following manner... const Landmark = require('../models/landmark'); function indexRoute(req, res, next) { Landmark .find() .exec() .then((landmark) => res.render('/landmarks/index', { l ...

Reorganize and Consolidate JSON Data

Among the myriad posts discussing JSON formatting, I have yet to find one that caters to my peculiar scenario. Here is the data source in question: data = [{ "LoanOfficer": "Brett", "Year": 2014, "Month": 10, "FundedVolume": 304032.0000, "FundedUnits": 2. ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

A dynamic jQuery plugin for creating captivating image slideshows

I am in need of a recommendation for a jQuery carousel plugin that has the capability to create a carousel similar to the one shown in the image. Specifically, I am looking for a carousel where the active image item moves to the center and becomes larger. ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...

Current Date using Handlebars

Does anyone know how to display today's date in a Handlebar file as "Today is Thursday"? <script> var today = new Date(); var day = today.getDay(); var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"]; ...

Rotating an SVG shape a full 360 degrees results in no visible change

Currently, I am utilizing d3.js for a project and encountering an issue with rotating an SVG element 360 degrees to achieve a full spin back to its original position. If I rotate the element 3/4 of the way using the following code snippet, it works effect ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

When attempting to use tunnel-ssh, the error message "TypeError: Object is not a function" is displayed

Currently, I am testing out the introductory example provided in a tutorial for the widely used NPM package called tunnel-ssh. Below is the code snippet that I have been executing: var tunnel = require('tunnel-ssh'); var config = { username: ...