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

Node.js连接MongoDB报错MongoServerSelectionError: this.signal.throwIfAborted is not a function

解决MongoServerSelectionError: this.signal.throwIfAborted is not a function错误

问题描述

使用Node.js连接MongoDB Atlas时遇到以下错误:

MongoServerSelectionError: this.signal.throwIfAborted is not a function

已将MongoDB Atlas的IP访问列表配置为0.0.0.0/0,代码如下:

const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config();

const port = process.env.PORT || 5000;

//middleware
app.use(cors());
app.use(express.json());

const { MongoClient, ServerApiVersion } = require("mongodb");
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.jmyw8mw.mongodb.net/?retryWrites=true&w=majority`;

// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
});

async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log(
      "Pinged your deployment. You successfully connected to MongoDB!"
    );
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

app.get("/", (req, res) => {
  res.send("Hello world");
});

app.listen(port, () => {
  console.log(`Study Materials is running on port ${port}`);
});

预期输出Pinged your deployment. You successfully connected to MongoDB!,但实际触发上述错误。

解决方案

这个错误的核心原因是Node.js版本与MongoDB Node.js驱动版本不兼容:MongoDB驱动v5及以上版本要求Node.js版本至少为v14.17.0,若你的Node.js版本低于该阈值,就会出现这个报错。

方案1:升级Node.js到LTS版本

  1. 检查当前Node.js版本:
    node -v
    
  2. 如果版本低于v14.17.0,升级到最新的LTS版本(推荐v18.x或v20.x),可以通过nvm(Node版本管理器)操作:
    • 安装LTS版本:
      nvm install --lts
      
    • 切换到该版本:
      nvm use --lts
      

方案2:降级MongoDB驱动到兼容版本

如果暂时无法升级Node.js,可以安装兼容旧Node版本的MongoDB驱动(比如v4.x系列):

npm uninstall mongodb
npm install mongodb@4.17.0

额外检查

  • 确认.env文件中的DB_USER和DB_PASSWORD配置正确,无拼写错误
  • 重启项目后重新测试连接

内容的提问来源于stack exchange,提问作者Aurora Lithe Roy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:56:08