'Cannot read properties of undefined (reading 'path')

route file

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads');
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

router.post('/hiring', upload.single('resume'), (req, res, next) => {
  console.log(req.file);
  const hiring = new Hiring({
    _id: new mongoose.Types.ObjectId(),
    username: req.body.username,
    email: req.body.gender,
    mobile: req.body.mobile,
    resume: req.file.path,
  });
  hiring
    .save()
    .then((result) => {
      console.log(result);
      res.status(200).json({
        message: 'Created user successfully',
        createdUser: {
          _id: result._id,
          username: result.username,
          email: result.email,
          mobile: result.mobile,
          resume: result.resume,
        },
      });
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({
        error: err,
      });
    });
});

I am trying to post data in database through postman but it is getting error 'path undefined'. I tried to change folder path like './uploads/', '/uploads', 'uploads/' and 'uploads' but the problem is not solving.

error

TypeError: Cannot read properties of undefined (reading 'path')

please give the solution for this problem.



Solution 1:[1]

It appears req.file is undefined. which itself meant you are not uploading file via postman.

You have to attach file in postman with 'resume' as keyword after selecting mutlipart in body section.

check this screenshot

With dothttp It would look like this

POST 'http://localhost:3000/hiring'
multipart(
    'resume'< '<replace path to the resume here>',
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1