[node.js] Mongodb: failed to connect to server on first connect

I get the following error:

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' }

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) 

It kinda looks like there is a connection..

I've tried both

$ mongod 

and

$ brew services start mongo 

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);
 });

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.

I've tried both "localhost" and "127.0.0.1?". I'm on OSX 10.11.5 I'm running Node 7.3.0 and Mongo 3.2.9

What am I doing wrong? How do I figure out what's wrong?

This question is related to node.js mongodb mongoose

The answer is


In case of remote db in cloud such as ATLAS, you should create whitelist entry 0.0.0.0/0. This allows you to access your cluster ATLAS from any IP address.

enter image description here


I tried all the method above.

  • Allowed access from any db,
  • Verified correct credentials of connection string,
  • Created another user,

Nothing of those worked for me.

Finally, I created a new DB and switched to it. everything was fine. Luckily, it wasn't so important DB (for self education purpose) so the damage wasn't so big.


if it is cluster MongoDB then you need to add your current IP to the cluster, to add your current IP address you need to complete few steps below-

step 1- go to login page of Mongodb and login with valid credential - https://cloud.mongodb.com/user#/atlas/login
step 2- CLick Network Access from left sidebar under Security Section
Step 3 - Click Add IP Address
Step 4 - Click Add Current IP Address or Allow Connection From Any Where
now try to connect - npm start

enter image description here

and for Local MongoDB use mongo String like "mongodb+srv://username:pass%[email protected]/test?retryWrites=true&w=majority"

password must be encoded like example string


If the mongo instance is build on the cloud.mongodb.com this error appears when the instance can work only from known IP addresses set in the IP whitelist pool when the instance was configured.

So from the mongo dashboard need to be set the current IP address on the IP whitelist from network access menu on the left.

BR,


I was trying to connect mlab with my company wifi connection and it was giving this error. But when I switched to personal network it worked and got connected.


I was running mongod in a PowerShell instance. I was not getting any output in the powershell console from mongod. I clicked on the PowerShell instance where mongod was running, hit enter and and execution resumed. I am not sure what caused the execution to halt, but I can connect to this instance of mongo immediately now.


I was getting same error while I tried to connect mlab db that is because my organization network has some restriction, I switched to mobile hotspot and it worked.


I connected to a VPN and it worked. I was using school's WiFi.


Local MongoDb problem solution

solve it by following the below steps:

Changed

mongodb://localhost:27017/local

to

localhost/local

And the error gone


While connected to a wifi network, mongodb://localhost/db_name worked as expected.

When I wasn't connected to any wifi network, this couldn't work. Instead I used, mongodb://127.0.0.1/db_name and it worked.

Probably a problem to do with ip configurations.


Adding one more answer as the solution is from different contexts:

MongoDb Atlas problem solution

I connected to MongoDB Atlas and whitelisted my machine's IP by following the below steps:

  • Go to the security tab

the security tab

  • Go to the network access tab under the security tab

network access tab under security tab

  • Go to the IP whitelist tab

IP whitelist tab



I ran into this issue serval times, and here is some troubleshooting list

  1. make sure database path is exist, the default path in windows in C:\data\db
  2. make sure mongo is running, to run it go to C:\Program Files\MongoDB\Server\3.4\bin and run the following:
    1. mongod.exe
    2. mongo.exe
  3. make sure that your connection string is correct like mongodb://localhost/database-name

For me,issue was mongo was not running.So first i started "mongod" command in the console.And later in another console tab I have run "mongo". Now the connection is successful. Now run your app your problem should be solved.


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to mongoose

Querying date field in MongoDB with Mongoose Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Mongodb: failed to connect to server on first connect Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongoError: Topology was destroyed Difference between MongoDB and Mongoose How can you remove all documents from a collection with Mongoose? E11000 duplicate key error index in mongodb mongoose