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

MongoDB连接异常:警告导致应用无法启动的问题求助

解决Node.js连接MongoDB的废弃警告及运行异常问题

问题重现

运行Node.js应用时出现以下废弃警告,且导致应用无法正常启动:

DepracationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

[MONGODB DRIVER] Warning: Current Server Discover and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to MongoClient constructor

应用中MongoDB连接相关核心代码片段如下:

const MONGODB_URI =
  'mongodb+srv://mateoghidini:<PASSWORD>@cluster0.9dernor.mongodb.net/test';

const app = express();
const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions'
});

// ... 中间件与路由配置 ...

mongoose
  .connect(MONGODB_URI)
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });

原因分析

这些警告并非单纯提示,而是因为mongoose及connect-mongodb-session依赖的MongoDB驱动版本要求启用新连接配置项。旧连接逻辑在新版本驱动中可能出现连接失败,进而导致应用无法启动。

你的依赖包并非全部过时,但部分配置未跟上驱动版本要求:

  • body-parser在Express 4.16.0+已内置,可替换为express.urlencoded({ extended: false }),但不影响当前运行;
  • csurf包已被官方标记为废弃,长期建议迁移至csrf包;
  • 其他包如express-session、multer、connect-flash只要保持最新版本,配合正确配置即可正常使用。

修复步骤

需要在两个连接MongoDB的地方添加必填配置项:

1. 修改MongoDBStore的配置

connect-mongodb-session内部使用MongoClient,需添加新的解析器和拓扑配置:

const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions',
  useNewUrlParser: true,
  useUnifiedTopology: true
});

2. 修改mongoose.connect的配置

在mongoose连接时传入配置对象,启用新的连接逻辑:

mongoose
  .connect(MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false // 可选,避免findByIdAndUpdate等方法的废弃警告
  })
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });

完成以上修改后,重新启动应用,警告会消失,应用也能正常连接MongoDB并运行。

内容的提问来源于stack exchange,提问作者tukitooo1998

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:50:32