Error in when updating an item in Node?

Hi guys, I keep getting an error when I try to update an item in my node app. I get the error " Cannot read property ‘filename’ of undefined" and it points to line 26 in my item.js file in the rotes folder.

I want to to be able to update my items and when I don’t update but the update button is pressed then the default value set in my input fields stays the same for my item. I used multer to upload the images.

Here’s the repo: GitHub - pllealfunes/pet-store

item.js

var express = require('express');
var itemRouter = express.Router();
var items = require('../models/itemsSchema');
var multer = require('multer');
var photoController = require('../controllers/photoController');
var upload = multer({ storage: photoController.storage, fileFilter: photoController.imageFilter })


/* GET users listing. */
itemRouter.get('/:itemid', function (req, res, next) {
    items.findOne({
        '_id': req.params.itemid
    })
        .then((item) => {
            res.render('item', { item: item })
        })
        .catch((err) => {
            if (err) {
                res.end("ERROR!");
            }
        });
});

// where I try to update an item
itemRouter.post('/:itemid', upload.single('image'), (req, res, next) => {
    const photo = "/images/" + req.file.filename;
    items.findOne({
        '_id': req.params.itemid
    })
        .then((item) => {
            var data = {
                name: req.body.name,
                description: req.body.description,
                category: req.body.category,
                price: req.body.price,
                instock: req.body.instock,
                imageurl: photo
            }
            item.set(data);
            item.save().then(() => {
                res.redirect(`/item/${item.id}`);
            });
        }).catch((err) => {
            if (err) console.log(err);
        });
});



itemRouter.get('/delete/:itemid', (req, res, next) => {
    items.deleteOne({
        '_id': req.params.itemid
    })
        .then(() => {
            res.redirect('/');
        })
        .catch((err) => {
            if (err) console.log(err);
        });
});

module.exports = itemRouter;

item.pug

extends layout

block content
  img(src=item.imageurl, width="250")
  h1= item.name
  p.description Description: #{item.description}
  p Category: #{item.category}
  p.item-price Price: $#{item.price}
  p.item-instock Instock: #{item.instock}
  p.item-created-time Created At: #{item.createdAt}
  p.item-updated-time Updated At: #{item.updatedAt}

  h2 Edit Your Post:
  form(class="editForm" method='POST' action="/item/"+item._id enctype="multipart/form-data")
            div.form-group
            label(for='image')
            input(placeholder='Image' type='file' name='image' value=item.description)
            div.form-group
            label(for='name')
            input(type='text', value=item.name name='name')
            div.form-group
            label(for='category')
            input(type='text', value=item.category name='category')
            div.form-group
            label(for='price')
            input(type='text', value=item.price name='price')
            div.form-group
            label(for='instock')
            input(type='text', value=item.instock name='instock')
            div.form-group
            label(for='description')
            textarea.description-box(cols="50", rows="10" name='description') #{item.description}
            br
            button.update-button(type='submit') Update Item
  br
  h2 Delete Inventory Item
  p Before deleting an item be sure if this is what you want. Items that are deleted cannot be recovered.
  br
  a.delete-button(href='/item/delete/'+item._id) Delete Item

This just means that req.file is undefined. What you need to do then is handle this case somehow. That could be as simple as

if (!req.file) {
     res.status(404);
     return;
}

Of course, it’s up to you to determine how you want to handle if the file is undefined, and then you can design it however you want in the frontend as well.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.