I was using formidable@2.0.1 to upload form that contents image, following a tutorial thou. I got the below. How to debug this error?
Error: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
Controller.js
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");
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({
error: "Image could not be uploaded",
});
}
let project = new Project(fields);
if (files.image) {
project.image.data = fs.readFileSync(files.image.path);
project.image.contentType = files.image.type;
}
project.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(error),
});
}
res.json(result);
});
});
};
projectModel.js
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const projectSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
require: true,
},
category: {
type: ObjectId,
ref: "Category",
required: true,
},
image: {
data: Buffer,
contentType: String,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Project", projectSchema);
In Controller.js I changed files.image.path
to files.image.filepath
and also changed files.image.type
to files.image.mimetype
Controller.js
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");
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({
error: "Image could not be uploaded",
});
}
let project = new Project(fields);
if (files.image) {
project.image.data = fs.readFileSync(files.image.filepath);
project.image.contentType = files.image.mimetype;
}
project.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(error),
});
}
res.json(result);
});
});
};