使用Mongoose遇报错:Model.findById()不再支持回调函数
解决MongooseError: Model.findById() no longer accepts a callback
问题原因
新版本Mongoose已移除findById()方法的回调参数支持,必须采用Promise链式调用或async/await语法处理异步操作。
修复方案
方案1:使用async/await(推荐)
将函数改为异步函数,通过try/catch捕获错误:
module.exports.profile = async function(req, res){ if(req.cookies.user_id){ try { const user = await User.findById(req.cookies.user_id); if(user){ return res.render('user_profile', { title: "User Profile", user: user }) } return res.redirect('/users/sign-in'); } catch (err) { console.error(err); return res.redirect('/users/sign-in'); } }else{ return res.redirect('/users/sign-in'); } }
方案2:使用Promise链式调用
若偏好Promise风格,可通过.then()和.catch()处理结果与错误:
module.exports.profile = function(req, res){ if(req.cookies.user_id){ User.findById(req.cookies.user_id) .then(user => { if(user){ return res.render('user_profile', { title: "User Profile", user: user }) } return res.redirect('/users/sign-in'); }) .catch(err => { console.error(err); return res.redirect('/users/sign-in'); }); }else{ return res.redirect('/users/sign-in'); } }
关键提示
- Mongoose v6.x及以上版本强制使用Promise风格异步API,不再支持回调参数。
- 必须添加错误处理逻辑,避免未捕获的Promise异常引发服务器故障。
内容的提问来源于stack exchange,提问作者Suneel Nerre
相关产品推荐
相关产品推荐

