我已经创建了使用 multer gridfs 上传 mp3 的 API,然后使用 Postman 进行测试。我得到了
无法读取未定义的属性(读取“_id”)
错误,但是我在MongoDB Atlas上检查了
uploads.files
和uploads.chunks
,文件已经上传了,这是配置
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);
这是这里的错误:
^
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```
错误“无法读取未定义的属性(读取'_id')”表明
req.file
在您的 trackController.postTrack
方法中未定义。以下是解决问题的几个步骤:
upload.single("file")
。console.log(req.file);
router.post("/track/upload", (req, res, next) => {
upload.single("file")(req, res, (err) => {
if (err) return res.status(500).send(err.message);
trackController.postTrack(req, res);
});
});
multer
和 multer-gridfs-storage
的兼容版本。如果
req.file
仍未定义,请验证文件是否正确上传以及您的 Postman 请求是否配置正确。