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

React上传图片至MongoDB GridFS时出现TypeError: Cannot read '_id'问题求助

问题排查与修复方案

核心错误原因

报错TypeError: Cannot read properties of undefined (reading '_id')来自multer-gridfs-storage内部,根源是文件配置函数返回了undefined:在uploadFilesMiddleware.js的file回调中,捕获到文件格式错误后仅打印日志,未重新抛出错误或返回有效配置对象,导致存储引擎无法获取合法的文件元数据,后续处理时触发undefined访问错误。

分步修复

1. 修复文件配置函数的错误处理

修改uploadFilesMiddleware.js中的file回调,确保捕获错误后重新抛出,让存储引擎正确处理错误:

const storage = new GridFsStorage({
  url: process.env.MONGO_URI,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    try {
      const match = ["image/png", "image/jpeg", "image/jpg"];
      if (match.indexOf(file.mimetype) === -1) {
        throw new Error("Invalid file format");
      }
      console.log("image-bucket: ", process.env.IMAGE_BUCKET);
      console.log("upload-file: ", file);
      return {
        bucketName: process.env.IMAGE_BUCKET,
        filename: `${Date.now()}-${process.env.BUSINESS}-${file.originalname}`,
      };
    } catch (error) {
      console.log("error: ", error);
      throw error; // 关键:重新抛出错误,避免返回undefined
    }
  },
});

2. 移除客户端不必要的Content-Type设置

axios发送FormData时会自动生成带boundary的正确Content-Type,手动设置会导致请求格式错误,删除客户端uploadFileHandler中的对应配置:

const config = {
  headers: {
    // 删掉这一行:"Content-Type": "multipart/form-data",
    Authorization: `Bearer ${userInfo.token}`,
  },
};

3. 清理冗余的MongoDB连接代码

uploadController.js中创建的mongoClient、database、image、bucket变量未被使用,且未执行连接操作,直接删除这部分代码避免潜在问题:

// 删掉以下冗余代码
const mongoClient = new MongoClient(process.env.MONGO_URI);
const database = mongoClient.db(process.env.DATABASE);
const image = database.collection(process.env.IMAGE_BUCKET + ".files");
const bucket = new GridFSBucket(database, {
  bucketName: process.env.IMAGE_BUCKET,
});

4. 完善控制器的错误返回格式

uploadController.js中的错误返回模板字符串语法错误,修改为模板字符串:

return res.send({
  message: `Error when trying upload image: ${error}`, // 把单引号改成反引号
});

验证步骤

  1. 重启服务端与客户端
  2. 选择合法格式的图片(png/jpg/jpeg)上传,验证是否成功
  3. 选择非法格式文件,验证是否返回正确的错误提示而非崩溃

内容的提问来源于stack exchange,提问作者Streuby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:57:39