[MongoDB] Error: failed to connect to [localhost:27017]

Node.js (Express) + MongoDB という構成のウェブアプリケーション開発でアプリ起動時 (node-dev app.js) に、下記のようなエラーが発生しました。

MongoDB | モンゴディービー

Webアプリから一切 mongo に接続できなくなりました。CLIからは接続できました。

[ERROR] 21:57:58 Error
Error: failed to connect to [localhost:27017]
    at null.<anonymous> (/Users/your_username/git/com/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:540:74)
    at EventEmitter.emit (events.js:106:17)
    at null.<anonymous> (/Users/your_username/git/com/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
    at EventEmitter.emit (events.js:98:17)
    at Socket.<anonymous> (/Users/your_username/git/com/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
    at Socket.EventEmitter.emit (events.js:95:17)
    at net.js:830:16
    at process._tickCallback (node.js:415:13)

試行錯誤したものの解決せず、結局、mongodb を再インストールしました。

% brew uninstall mongodb                                             
Uninstalling /usr/local/Cellar/mongodb/2.4.8...
 
% brew install mongodb

インストールにあまり時間が掛からないなら良いんですけど、mongodb はコンパイルに数分ぐらい掛かるので、毎回再インストールするのはちょっとつらいです。

ちなみに、試行錯誤したのは下記のとおりです。

mongod.lock 消して再起動したり、–repair も試してみましたがダメでした。

% ps aux | grep mongo                  
your_username           572   0.0  0.4  2721360  36264   ??  S    10:00PM   0:00.61 /usr/local/opt/mongodb/mongod run --config /usr/local/etc/mongod.conf
your_username           896   0.0  0.0  2432784    600 s003  S+   10:04PM   0:00.00 grep mongo
 
% launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
 
% ps aux | grep mongo        
your_username           982   0.0  0.0  2432784    608 s003  S+   10:07PM   0:00.00 grep mongo
 
% rm /usr/local/var/mongodb/mongod.lock
 
% launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
 
% ps aux | grep mongo                                                
your_username          1060   0.0  0.0  2432784    604 s003  S+   10:11PM   0:00.00 grep mongo
your_username          1052   0.0  0.4  2712144  34696   ??  S    10:11PM   0:00.06 /usr/local/opt/mongodb/mongod run --config /usr/local/etc/mongod.conf

解決方法を御存じの方がいらっしゃいましたら、教えて頂けると助かります。

追記: Error: failed to connect to [localhost:27017] 解決しました

未だ解決しておらず、この症状が発生した場合、「システム終了」→「起動」で対応しています。(再起動だとダメ)

無事に解決しました。(2013/12/17)

原因は、アプリケーションから localhost:27017 に繋ぎにいっていたのですが /etc/hosts の中が何も書かれていなかったので localhost に接続できなかったということでした。

アプリケーション側で mongodb への接続設定を書いている箇所を 127.0.0.1 へ変更するか、/etc/hosts を修正するのどちらかで対応可能でした。

hosts file の管理は hoster ってMac用のアプリを使っていたのですが、これが悪さをしていたのかもなのでゴミ箱へダンクシュートしておきました。