使用Mongoose结合Cloudinary更新带图个人资料报回调类型错误
报错根因
触发Callback must be a function, got [object Object]错误的核心原因是User.updateOne的参数传递完全不符合Mongoose的接口规范:
- 参数顺序、数量错误:Mongoose的
updateOne最多接收4个参数,固定顺序为过滤条件 -> 更新内容 -> 配置项 -> 回调函数,你的代码里传了5个参数,在第四个参数位置传入了{ new: true }对象,Mongoose会把这个位置的参数识别为回调函数,发现不是函数类型就直接抛出该错误 - 更新内容被错误拆分:你把req.body的更新字段、profileImage字段拆成了两个独立对象作为第二、第三个参数传入,Mongoose根本不会识别到你要更新profileImage字段
- 异步写法混用:你同时用了
async/await和回调函数两种异步写法,逻辑容易冲突
修复后代码(async/await 写法,和你现有代码风格一致)
updateProfile: async function(req, res) { try { const update = req.body; const id = req.params.id; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.'); } const image = req.files.profileImage; const cloudFile = await upload(image.tempFilePath); const profileImage = cloudFile.url; console.log('Loging cloudfile', profileImage); // 按正确参数顺序调用:过滤条件、更新内容、配置项,async/await 写法不需要传回调 const updateResult = await User.updateOne( { _id: id }, { $set: { ...update, profileImage } }, { runValidators: true } // 建议加该配置,更新时会触发Schema定义的字段校验 ); if (updateResult.modifiedCount === 1) { return res.status(200).send({ success: true, msg: 'Profile updated successfully' }) } return res.status(404).send({ success: false, msg: 'User not found or no content changed' }) } catch (error) { res.status(500).json({ msg: error.message }); } }
补充说明
- 你之前写的
{ new: true }配置是给findOneAndUpdate、findByIdAndUpdate这类需要返回更新后文档的接口用的,updateOne本身只返回匹配条数、修改条数这类统计信息,不返回更新后的文档,所以这个配置对updateOne无效。如果你需要拿到更新完成后的用户完整数据,可以把updateOne替换成findByIdAndUpdate,示例写法:
const updatedUser = await User.findByIdAndUpdate( id, { $set: { ...update, profileImage } }, { new: true, runValidators: true } ); if (updatedUser) { return res.status(200).send({ success: true, msg: 'Profile updated successfully', data: updatedUser }) }
- 原代码返回字段存在拼写错误:
sucess应为success,successful应为successfully,修复时已经一并调整。
内容的提问来源于stack exchange,提问作者Hemmyhtec Creatives
相关产品推荐
相关产品推荐

