MongoError:第一次连接时无法连接到服务器[localhost:27017](ECONNREFUSED)

时间:2017-08-24 10:16:26

标签: node.js mongodb windows-firewall econnrefused

我刚刚将MongoDB添加到使用npm init命令创建的Node.js项目的依赖项中。我的index.js代码是:

var MongoClient = require('mongodb').MongoClient
, assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/mydatabase';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");

db.close();
});

但是当我执行代码时会抛出以下错误:

AssertionError: null == { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

我真的不知道如何解决它。我跟踪了一些报告相同错误的指南,但我无法修复它。

我应该在调制解调器上打一个端口吗?我应该用我的IP替换“localhost”吗?我该怎么办?

请帮助我!

更新

我在Android设备上安装了MongoDB服务器,并将url变量替换为mongodb://ANDROID-DEVICE-LOCAL-IP:27017/mydatabase,现在可以正常使用。

如何将数据库放在计算机上?防火墙阻止传入连接吗?这是为什么它适用于Android但不适用于Windows?

2 个答案:

答案 0 :(得分:1)

我解决了这个问题!

我在cmd中运行了mongod -dbpath "MY-PATH",现在可以正常运行了。

发生错误是因为没有在27017端口上侦听。现在mongod程序正在侦听该端口上的连接,因此我的项目连接不再被拒绝。

答案 1 :(得分:0)

制作类似config.js

的配置文件
module.exports = {
    'secretKey': '12345-67890-09876-54321',
    'mongoUrl' : 'mongodb://localhost:27017/cubs'
}

并在服务器代码中要求该文件

var config = require('./config');
var mongoose = require('mongoose');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log("Connected correctly to server");
});
相关问题