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

MongoDB Node.js中“Callbacks are deprecated”报错问题求助

解决MongoDB Node.js驱动回调弃用警告问题

你的报错核心原因是MongoDB Node.js驱动的回调式MongoClient.connect已被标记为弃用,这和useUnifiedTopology参数无关,也不需要重装或降级驱动,直接改用Promise/async-await的现代写法即可解决。

修改后的代码示例

const { MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017/";

async function fetchSortedCustomers() {
  let client;
  try {
    // 连接数据库
    client = await MongoClient.connect(url, { useUnifiedTopology: true });
    const dbo = client.db("mydb");
    const mysort = { name: 1 };
    // 查询并排序
    const result = await dbo.collection("customers").find().sort(mysort).toArray();
    console.log(result);
  } catch (err) {
    console.error(err);
  } finally {
    // 确保数据库连接正常关闭
    if (client) {
      await client.close();
    }
  }
}

// 执行查询函数
fetchSortedCustomers();

关键说明

  • 用async-await替代嵌套回调,这是MongoDB驱动官方推荐的写法
  • 通过try-catch-finally结构统一处理错误和资源释放,避免连接泄漏
  • 保留useUnifiedTopology: true参数,这是适配新版MongoDB集群的必要配置

如果非要继续使用回调写法,可以安装mongodb-legacy兼容包,但官方强烈建议优先采用Promise/async-await的现代方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:50:42