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
...