node.js - 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";
提前致谢!
解决方案
大部分时间都会发生这种情况可能存在IP限制问题或解决此问题的任何其他方法有两种方法
- 使用 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 的连接字符串
推荐阅读
- python - sys.argv 列表索引超出范围错误
- html - 高度:自动扩展最小高度
- spring - 无法将类型为“java.lang.String”的属性值转换为所需类型“java.time.LocalDate”,用于百里香形式的属性“日期”
- html - 改变孩子在表格中的位置 - CSS
- javascript - JavaScript中的增量正确性递归算法
- .htaccess - Htaccess 重定向始终保留旧路径
- apache-spark - sparklyr 寻找使用时间序列的方法(hts、预测、timekit 或预言机)
- r - R网状无法找到已安装的python库
- entity-framework - VSTS Build 如何为 EF Core Code First 添加 update-database 命令
- javascript - 我如何使用 javascript 验证复选框?