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

使用multer-gridfs上传MP3时触发Cannot read _id未定义错误

multer-gridfs上传MP3后报错Cannot read properties of undefined (reading '_id')问题解决

问题情况

  • 用multer-gridfs搭建MP3上传API,Postman测试时弹出错误:

Cannot read properties of undefined (reading '_id')

  • 但MongoDB Atlas里的uploads.files和uploads.chunks集合已经成功收到上传的文件。

错误栈信息

TypeError: Cannot read properties of undefined (reading '_id')
    at GridFSBucketWriteStream.emitFile (D:\nemoth\sound_seed\node_modules\multer-gridfs-storage\lib\gridfs.js:306:31)
    at GridFSBucketWriteStream.emit (node:events:530:35)
    at finish (node:internal/streams/writable:955:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:90:21)

Node.js v22.11.0

当前配置代码

const storage = new GridFsStorage({
  url: process.env.MONGO_URI,
  file: (req, file) => {
    if (file.mimetype === "audio/mp3" || file.mimetype === "audio/mpeg") {
      return {
        filename: Date.now() + path.extname(file.originalname),
        bucketName: "uploads",
      };
    }
    return console.log("wrong file type:" + file.mimetype);
  },
});

const upload = multer({ storage });
router.post("/track/upload", upload.single("file"), trackController.postTrack);

问题原因&修复方案

原因

问题出在file回调函数的返回值上:当文件类型不符合要求时,你返回的是console.log()的执行结果(也就是undefined),但multer-gridfs-storage要求这个回调必须始终返回一个对象或者Promise,哪怕是处理错误场景。文件能成功写入是因为报错发生在上传完成后的emitFile阶段——此时文件已经存入GridFS,但库尝试读取回调返回对象的_id字段时,因为返回值是undefined,直接触发了类型错误。

修复代码

把不符合类型的分支改成抛出错误或者返回拒绝的Promise,确保所有分支都有合法返回值:

file: (req, file) => {
  if (file.mimetype === "audio/mp3" || file.mimetype === "audio/mpeg") {
    return {
      filename: Date.now() + path.extname(file.originalname),
      bucketName: "uploads",
    };
  }
  // 直接抛出错误,让multer捕获并处理
  throw new Error(`wrong file type: ${file.mimetype}`);
  // 也可以返回拒绝的Promise,适合异步场景
  // return Promise.reject(new Error(`wrong file type: ${file.mimetype}`));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:33:19