I am getting the following errors when doing some changes but they never get resolved
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
This is happening when I am trying to create a product and uploading an image over postman, please resolve I am in need
Screenshots of code
app.js app.js
Product Route.js' Product.js
Product Controller.js Product Controller
Product Model Product model
Code if image not appears
ProductRoute -
const express = require("express")
const router = express.Router()
const { create } = require("../controllers/product")
const { requireSignin, isAdmin, isAuth } = require("../controllers/auth")
const { userById } = require("../controllers/user")
//Routes
router.post("/product/create/:userId", requireSignin, isAdmin, create)
router.param("userId", userById)
module.exports = router
Product Controller-
const formidable = require("formidable")
const _ = require("lodash")
const fs = require("fs")
const Product = require("../models/product")
const { errorHandler } = require("../helpers/dbErrorHandler")
exports.create = (req, res) => {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
err: "Image cannot be uploaded",
})
}
let product = new Product(fields)
if (files.photo) {
product.photo.data = fs.readFileSync(files.photo.path)
product.photo.contentType = files.photo.type
}
product.save((err, result) => {
if (err) {
console.log(err)
}
res.json(result)
})
})
}
In Product Controller, change the files.photo.path to files.photo.filepath and also changed files.photo.type to files.photo.mimetype
Product Controller
const formidable = require("formidable")
const _ = require("lodash")
const fs = require("fs")
const Product = require("../models/product")
const { errorHandler } = require("../helpers/dbErrorHandler")
exports.create = (req, res) => {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
err: "Image cannot be uploaded",
})
}
let product = new Product(fields)
if (files.photo) {
product.photo.data = fs.readFileSync(files.photo.filepath)
product.photo.contentType = files.photo.mimetype
}
product.save((err, result) => {
if (err) {
console.log(err)
}
res.json(result)
})
})
}