I tried to add image in database with mongo db schema but when I test my Api request with postman my terminal give error?

Viewed 17

The error give by my terminal is I dont know why this give the error beacause I created the another file in which only image post in the databse of mongodb and its work but here its throw this kind of type error.

TypeError: Cannot read properties of undefined (reading 'filename')
    at C:\Users\Dell\Desktop\cinemaapp\backend\routes\category.js:31:27
    at Layer.handle [as handle_request] (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\layer.js:95:5)     
    at next (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\layer.js:95:5)     
    at C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:175:3)
    at router (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:47:12)

The category.js code is

const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const Product=require('../models/Product');
const multer=require('multer');


//storage

const storage = multer.diskStorage({
    destination: 'uploads',
    filename: function (req, file, cb) {
       cb(null,file.originalname)
    }
  })

  const upload = multer({ storage: storage }).single('testImage');


router.post('/addproduct',[], async (req, res) => {
try {
    const { name, description, price,category } = req.body;
    //if there are errors ,return bad request and the error
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    const note = new Product({
        name, description,price,category,
        image:{
            data:req.file.filename,
            contentType:'image/png '
        }
    })
    const savenote=await note.save();
    res.json(savenote);
} catch (error) {
    console.log(error);
}
    
});
module.exports=router;

The model schemaa for this is

const mongoose = require('mongoose');
const { Schema } = mongoose;
const ProductSchema = new Schema({

    name: {
        type: String,
        required: [true, "Please Enter product Name"],
        trim: true
    },
    description: {
        type: String,
        required: [true, "Please write description of product"]
    },
    price: {
        type: Number,
        required: [true, "Please Enter the Price"],
        maxLength: [15, "Price cannot exceed 8 figure amount"]
    },
    category: {
        type: String,
        required: [true, "Category is must"]
    },
    image:{
        data:Buffer,
        contentType:String
    }

});
const Product=mongoose.model('product',ProductSchema);
module.exports=Product;

index.js code is

const connectToMongo=require('./db');
var cors = require('cors');
const express = require('express')

connectToMongo();
const app = express()
app.use(cors())
const port = 5000


app.use(express.json());
app.use('/api/authent',require('./routes/authent'));
app.use('/api/Categories',require('./routes/Categories'));
app.use('/api/category',require('./routes/category'));
app.use('/api/Imageprac',require('./routes/Imageprac'));

app.listen(port, () => {
  console.log(`iNoteBook Backend listening on port ${port}`)
})
1 Answers

Looks like you haven't placed multer middleware (upload) into your upload routes. That is the only reason why you are not receiving any files from your frontend and req.file is undefined. first of all add multer middleware to your upload route multer doc

As specified in multer readme. For more info: https://www.npmjs.com/package/multer

In your case instead of [], you can replace it with upload

Related