multer-gridfs 错误“TypeError:无法读取未定义的属性(读取'_id')”

问题描述 投票:0回答:1

我正在努力创建 WhatsApp 克隆并实现文件共享功能。一切都很顺利,直到我遇到这个导致我的后端崩溃的错误。奇怪的是,我可以在 MongoDB 中看到该文件,但错误仍然存在。我希望有人能帮我解决这个问题。

以下是所发生事件的摘要:

我的 WhatsApp 克隆应用程序中有文件共享功能。 当用户尝试共享文件时,它会保存到 MongoDB。 我可以确认该文件存在于 MongoDB 数据库中。 但是,后端因我似乎无法解决的错误而崩溃。 我不知道从哪里开始解决这个问题。任何人都可以提供有关可能导致此问题的原因的见解吗?在 MongoDB 数据库中处理文件共享时,我可能会犯一个常见错误吗?

我无法在这里发布我的所有代码,我的问题太长了[这是我的 github 链接][1]

api.js

export const uploadFile = async (data) => {
    try {
        return await axios.post(`${url}/file/upload`, data);
    } catch (error) {
        console.log('Error while calling uploadfile API ', error);
    }
}

控制器

const url = 'http://localhost:8000';
export const uploadFile = async(request, response)=>{
    if(!request.file){
        return response.status(404).json("file not found")
    }
    const imageUrl = `${url}/file/${request.file.filename}`;
    return response.status(200).json(imageUrl);
}

route.js

//Route for file upload
route.post('/file/upload', upload.single("file"), uploadFile);

错误

C:\Users\user\OneDrive\Documents\webdev\whatsapp clone self\server\node_modules\multer-gridfs-storage\lib\gridfs.js:306
                        id: f._id,
                              ^

TypeError: Cannot read properties of undefined (reading '_id')       
    at GridFSBucketWriteStream.emitFile (C:\Users\Siddh\OneDrive\Documents\webdev\whatsapp clone self\server\node_modules\multer-gridfs-storage\lib\gridfs.js:306:31)
    at GridFSBucketWriteStream.emit (node:events:526:35)
    at finish (node:internal/streams/writable:807:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Node.js v20.9.0
[nodemon] app crashed - waiting for file changes before starting...
javascript node.js mongodb gridfs multer-gridfs-storage
1个回答
0
投票

标题:multer-gridfs错误“TypeError:无法读取未定义的属性(读取'_id')”的解决方案

答案:

您似乎遇到了 multer-gridfs 的问题,该问题可能与您的 MongoDB 版本的兼容性有关。要解决此问题,请考虑将 MongoDB 版本降级到与 multer 和 multer-gridfs 兼容的版本。这是分步指南:

1。卸载 MongoDB:

npm uninstall MongoDB

2。安装兼容版本(例如5.9.1):

npm install [email protected]

这应该有助于解决您面临的“TypeError:无法读取未定义的属性(读取'_id')”问题。确保在进行这些更改后重新启动 Node.js 应用程序。

此外,检查 multer-gridfs 与 MongoDB 版本的兼容性矩阵也很重要。升级或降级软件包有时会引入其他兼容性问题,因此建议查看 multer-gridfs 和 MongoDB 的文档和发行说明。

如果问题仍然存在或在此过程中遇到任何其他问题,请随时提供更多详细信息或寻求进一步帮助。

© www.soinside.com 2019 - 2024. All rights reserved.