'Cannot read properties of undefined (reading 'path') - Multer Error
I am uploading an image to a folder in uploads via multer package. I am getting an error while testing the route in POSTMAN.
location_model.js
const util = require("util");
const locationSchema = mongoose.Schema(
{
_id: mongoose.Schema.Types.ObjectId,
name: String,
latitude: { type: Number, required: true },
longitude: { type: Number, required: true },
heightmapImage: { type: String, required: true },
},
{ bufferCommands: false } //no biffer time limit
);
module.exports = mongoose.model("Location", locationSchema);
This is the code for my location router while posting new location with image
router.post("/", upload.single("heightmapImage"), (req, res, next) => {
//Model
console.log(req.file);
console.log(req.file.path);
const location = new Location({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
latitude: req.body.latitude,
longitude: req.body.longitude,
heightmapImage: req.file.path
.replace(/\\/g, "/")
.substring("public".length),
});
location
.save()
.then((result) => {
//save method provided by mongoose, will save in the databas
console.log(result);
res.status(201).json({
//message: "Working POST",
message: "Created Location successfully",
createdLocation: {
name: result.name,
latitude: result.latitude,
longitude: result.longitude,
request: {
type: "GET",
url: "http://localhost:3000/location/" + result._id,
},
},
});
})
.catch((err) => {
console.log(err);
res.status(500).json({ error: err });
});
});
And this is the error while doing POST in Postman -
{
"error": {
"message": "Cannot read properties of undefined (reading 'path')"
}
}
Solution 1:[1]
It worked when I changed it to req.files
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 | sachin |