我使用以下示例代码从NodeJS连接到MongoDB时遇到问题。我试着运行“mongod”,有或没有sudo,但nodejs代码仍然无法连接。我可以使用“mongo”成功连接到数据库。
运行时间:Mac OS 10.6.8
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect("mongodb://localhost:27017/test", function(error, db) {
if(!error){
console.log("We are connected");
}
else
console.dir(error);
});
运行上述代码时出现以下错误:[错误:无法连接到[localhost:27017]]
也尝试了mongoose,但类似的错误:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("DB connected");
// yay!
});
输出:连接错误:[错误:无法连接到[localhost:27017]]
这是mongod的日志
mongod --help for help and startup options
2014-07-11T23:33:47.843-0700 kern.sched unavailable
2014-07-11T23:33:47.849-0700 [initandlisten] MongoDB starting : pid=29942 port=27017 dbpath=/data/db 64-bit host=usc8bcc8a0d0b1
2014-07-11T23:33:47.849-0700 [initandlisten]
2014-07-11T23:33:47.849-0700 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-07-11T23:33:47.849-0700 [initandlisten] db version v2.6.3
2014-07-11T23:33:47.849-0700 [initandlisten] git version: nogitversion
2014-07-11T23:33:47.849-0700 [initandlisten] build info: Darwin usc8bcc8a0d0b1 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
2014-07-11T23:33:47.849-0700 [initandlisten] allocator: system
2014-07-11T23:33:47.849-0700 [initandlisten] options: {}
2014-07-11T23:33:47.850-0700 [initandlisten] journal dir=/data/db/journal
2014-07-11T23:33:47.850-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-07-11T23:33:47.901-0700 [initandlisten] waiting for connections on port 27017
2014-07-11T23:34:47.901-0700 [clientcursormon] mem (MB) res:48 virt:2810
2014-07-11T23:34:47.901-0700 [clientcursormon] mapped (incl journal view):320
2014-07-11T23:34:47.901-0700 [clientcursormon] connections:0
5条答案
按热度按时间yhqotfr81#
没关系,我能够通过使用www.example.com而不是localhost来解决这个问题127.0.0.1,不知道为什么我必须使用IP地址。我的tomcat,apache,redis,甚至node server都使用localhost而不是mongodb。是否有配置,我需要改变,使其工作使用本地主机?
8iwquhpp2#
尝试在
/private/etc/hosts
文件中添加127.0.0.1 localhost
。roejwanj3#
./mongod --bind_ip localhost
uklbhaso4#
是的,我也遇到了这个错误,我的主机如下:
127.0.0.1 xxxxxx(the ip of my computer)
,当我在express项目中运行npm start
时,它得到了这样的错误。在我尝试将127.0.0.1
的Map更改为localhost
之后,它没有错误。a0zr77ik5#
Github上的一个人找到了一个解决方案:而不是写:
写:
(来源https://github.com/Automattic/mongoose/issues/5399)