You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MongoDB Schema添加图片时API请求出现TypeError问题

解决TypeError: Cannot read properties of undefined (reading 'filename')错误

我尝试通过MongoDB Schema将图片添加到数据库,用Postman测试API请求时终端抛出TypeError: Cannot read properties of undefined (reading 'filename')错误,错误位置在category.js第31行27列。之前单独实现图片上传的接口能正常工作,但当前接口出现这个类型错误。

错误栈信息

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)

相关代码

category.js

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;

Product模型Schema

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

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}`)
})

错误原因分析

这个错误的核心是req.file为undefined,说明multer没有正确解析到上传的文件,可能的原因:

  • 路由中未添加multer的upload中间件,导致文件未被处理,req.file不存在
  • Postman请求的文件字段名和multer配置的single('testImage')不匹配
  • 请求未以multipart/form-data格式发送

修复步骤

1. 给路由添加multer中间件

修改category.js中的路由,将upload加入请求处理链:

router.post('/addproduct', upload, [], async (req, res) => {
    // 原代码逻辑
})

这样multer才会处理上传的文件,req.file才会被正确赋值。

2. 检查Postman请求配置

  • 请求方法选POST,URL填写正确接口地址(如http://localhost:5000/api/category/addproduct)
  • 切换到Body标签,选择form-data格式
  • 文件字段名必须设为testImage(和multer的single('testImage')对应),再选择本地图片文件
  • 同时添加name、description、price、category文本字段,确保参数匹配

3. 修正Schema与数据存储的类型匹配(可选)

当前代码把req.file.filename(字符串)存到Schema中定义为Buffer类型的image.data,类型不匹配,需二选一调整:

  • 若仅存储文件名,修改ProductSchema:
    image:{
        data:String, // 改为String类型
        contentType:String
    }
    
  • 若存储文件Buffer内容,需读取文件:
    const fs = require('fs');
    // 创建Product实例时
    const note = new Product({
        name, description, price, category,
        image:{
            data: fs.readFileSync(req.file.path),
            contentType: req.file.mimetype // 自动获取文件类型,无需硬编码png
        }
    })
    

内容的提问来源于stack exchange,提问作者Mirza M Azeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:01:01