首页 > 解决方案 > MongoServerSelectionError:连接 ECONNREFUSED 127.0.0.1:27107

问题描述

我目前正在使用nodeJS(无猫鼬)测试MongoDB(4.4)驱动程序并尝试连接到localhost:27107。下面的代码几乎是从官方文档测试代码中复制/粘贴的。MongoDB 很好地在后面运行。但是,在我的命令行上,我收到如下所示的错误消息。谁能帮我解决这个问题?

错误信息:

MongoServerSelectionError:在listOnTimeout(内部/timers.js: 557:17) 在 processTimers (internal/timers.js:500:7) {原因:TopologyDescription {类型:'Single',setName:null,maxSetVersion:null,maxElectionId:null,服务器:Map(1) {'localhost: 27107' => [ServerDescription] },陈旧:false,兼容:true,compatibilityError:null,logicalSessionTimeoutMinutes:null,heartbeatFrequencyMS:10000,localThresholdMS:15,commonWireVersion:null } }

我在 app.js 中的代码如下所示;

const { MongoClient } = require("mongodb");

// Connection URI
const uri =
  "mongodb://localhost:27107";

// Create a new MongoClient
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function run() {
  try {
    // Connect the client to the server
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

const dbName = "fruitDB";

提前致谢!

标签: node.jsmongodb

解决方案


大部分时间都会发生这种情况可能存在IP限制问题或解决此问题的任何其他方法有两种方法

  1. 使用 mongoose 而不是 mongodb lib 这里是连接代码

  var mongoose = require('mongoose');
  var mongoDB = 'mongodb://127.0.0.1/my_database';
  mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));

2)如果您使用的是 atlas,则使用 2 或更低版本的 nodejs 的连接字符串


推荐阅读