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

求助:MongooseError报错Model.findById()不再接受回调函数

解决MongooseError: Model.findById() no longer accepts a callback错误

这个错误是因为Mongoose 6.x及以上版本彻底移除了findById()等CRUD方法的回调参数支持,只能使用Promise风格或async/await语法处理异步操作。结合你的报错位置(src/config/passport.js第27行),可以按以下两种方式修改代码:

方案1:使用async/await(推荐)

确保调用findById()的外层函数是async函数,用try/catch捕获错误:

// 示例:Passport验证函数中修改
passport.use(new YourStrategy(options, async (params, done) => {
  try {
    // 替换成你的Model和查询ID
    const targetDoc = await YourModel.findById(targetId);
    
    if (targetDoc) {
      return done(null, targetDoc);
    }
    return done(null, false);
  } catch (err) {
    return done(err, false);
  }
}));

方案2:使用Promise链式调用

如果不想用async/await,也可以用then()和catch()处理异步结果:

// 示例:替换原回调写法
YourModel.findById(targetId)
  .then(targetDoc => {
    if (targetDoc) {
      done(null, targetDoc);
    } else {
      done(null, false);
    }
  })
  .catch(err => {
    done(err, false);
  });

注意事项

  • 所有Mongoose的异步方法(如findOne()、create()等)都已不再支持回调,建议统一迁移到async/await语法,代码可读性更高。
  • 如果你的项目依赖的第三方库(如Passport)需要回调风格的函数,只需在回调内部使用async/await即可,如方案1所示。

内容的提问来源于stack exchange,提问作者Alexis Fernández

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:02:06