问题描述
我收到以下错误:
Warning { MongoError: failed to connect to server [mongodb:27017] on first connect
at Pool.<anonymous> (/Users/michaelks/Desktop/users/node_modules/mongodb-core/lib/topologies/server.js:325:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (/Users/michaelks/Desktop/users/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (/Users/michaelks/Desktop/users/node_modules/mongodb-core/lib/connection/connection.js:173:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at connectErrorNT (net.js:1025:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'MongoError',
message: 'failed to connect to server [mongodb:27017] on first connect' }
即使我在运行Mongo的终端窗口中获得了此信息:
Even though I get this in the terminal window where I run Mongo:
2016-12-25T03:45:23.715+0100 I NETWORK [initandlisten] connection accepted from 127.0.0.1:58868 #8 (8 connections now open)
看起来好像有连接.
我都尝试过
$ mongod
和
$ brew services start mongo
这是我的test_helper.js
This is my test_helper.js
const mongoose = require('mongoose');
mongoose.connect('mongodb:localhost/users_test');
mongoose.connection
.once('open', () => console.log('Good to go!'))
.on('error', (error) => {
console.warn('Warning', error);
});
我还没有专门将数据库设置为"users_test",因为我的印象是猫鼬或mongo或两者都将即时执行.
I have not specifically made the db "users_test" as I am under the impression that mongoose or mongo or both will do this on the fly.
我尝试了"localhost"和"127.0.0.1".我在OSX 10.11.5上我正在运行Node 7.3.0和Mongo 3.2.9
I've tried both "localhost" and "127.0.0.1".I'm on OSX 10.11.5I'm running Node 7.3.0 and Mongo 3.2.9
我做错了什么?我如何找出问题所在?
What am I doing wrong? How do I figure out what's wrong?
推荐答案
要连接至mongodb
与mongoose
一起使用,可以使用:
To connect to mongodb
with mongoose
, you can use :
mongoose.connect('mongodb://localhost/users_test');
或
mongoose.connect('localhost/users_test');
或
mongoose.connect('localhost','users_test');
但不是mongoose.connect('mongodb:localhost/users_test');
,它与正确的主机名(mongodb
而不是localhost
)不匹配
But not mongoose.connect('mongodb:localhost/users_test');
, it doesnt match the right hostname (mongodb
instead of localhost
)
这篇关于Mongodb:首次连接时无法连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!