[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


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

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


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.


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.


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 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.


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


Local MongoDb problem solution

solve it by following the below steps:

Changed

mongodb://localhost:27017/local

to

localhost/local

And the error gone


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


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 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.


Questions with node.js tag:

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` jwt check if token expired Using Environment Variables with Vue.js Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Can not find module “@angular-devkit/build-angular” MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client npx command not found await is only valid in async function What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? How to set bot's status Returning data from Axios API Error: EACCES: permission denied, access '/usr/local/lib/node_modules' ReferenceError: fetch is not defined ERROR in Cannot find module 'node-sass' Test process.env with Jest 'react-scripts' is not recognized as an internal or external command NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0' db.collection is not a function when using MongoClient v3.0 When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0) E: Unable to locate package npm How can the default node version be set using NVM? How to downgrade Node version How to solve npm install throwing fsevents warning on non-MAC OS? How to read file with async/await properly? Angular: Cannot Get / The difference between "require(x)" and "import x" Is there a way to force npm to generate package-lock.json? Angular - ng: command not found MongoError: connect ECONNREFUSED 127.0.0.1:27017 How can I use async/await at the top level? ERROR in ./node_modules/css-loader? Downgrade npm to an older version Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51 npm install Error: rollbackFailedOptional npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY How can I use an ES6 import in Node.js? Node.js: Python not found exception due to node-sass and node-gyp bash: npm: command not found? npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json' Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Questions with mongodb tag:

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? 'Field required a bean of type that could not be found.' error spring restful API using mongodb MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating MongoDB: Server has startup warnings ''Access control is not enabled for the database'' MongoDb shuts down with Code 100 Mongodb: failed to connect to server on first connect MongoDB what are the default user and password? MongoDB: How to find the exact version of installed MongoDB show dbs gives "Not Authorized to execute command" error How to join multiple collections with $lookup in mongodb $lookup on ObjectId's in an array How to enable authentication on MongoDB through Docker? How do you put an image file in a json object? Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongodb how to get max value from collections mongoError: Topology was destroyed MongoDB Data directory /data/db not found String field value length in mongoDB Uninstall mongoDB from ubuntu how to convert string to numerical values in mongodb MongoDB vs Firebase How to convert a pymongo.cursor.Cursor into a dict? E: Unable to locate package mongodb-org How to export JSON from MongoDB using Robomongo Difference between MongoDB and Mongoose Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version How to connect Robomongo to MongoDB Mongodb find() query : return only unique values (no duplicates) How can you remove all documents from a collection with Mongoose? Find duplicate records in MongoDB sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4 how can I connect to a remote mongo server from Mac OS terminal Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061 BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused How to list all databases in the mongo shell? TransactionRequiredException Executing an update/delete query How to select a single field for all documents in a MongoDB collection? MongoDB Show all contents from all collections Connection refused to MongoDB errno 111

Questions with mongoose tag:

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 Mongoose, Select a specific field with find Failed to load c++ bson extension How to define object in array in Mongoose schema correctly with 2d geo index Mongoose and multiple database in single node.js project Populate nested array in mongoose Cannot overwrite model once compiled Mongoose JavaScript OOP in NodeJS: how? Find document with array that contains a specific value Referencing another schema in Mongoose How can I generate an ObjectId with mongoose? Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id" How to check if that data already exist in the database during update (Mongoose And Express) Mongoose (mongodb) batch insert? Mongoose query where value is not null Mongoose, update values in array of objects What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"? Find MongoDB records where array field is not empty Mongoose delete array element in document and save Mongoose: Find, modify, save Mongoose: Get full list of users Mongoose limit/offset and count query Combine two OR-queries with AND in Mongoose nodejs mongodb object id to string How to populate a sub-document in mongoose after creating it? add created_at and updated_at fields to mongoose schemas What is the "__v" field in Mongoose MongoDB via Mongoose JS - What is findByID? MongoDB/Mongoose querying at a specific date? Comparing mongoose _id and strings How to get all count of mongoose model? Simplest way to wait some asynchronous tasks complete, in Javascript? How can I save multiple documents concurrently in Mongoose/Node.js? How to drop a database with Mongoose? Which SchemaType in Mongoose is Best for Timestamp? Convert Mongoose docs to json Mongoose.js: Find user by username LIKE value How to return a complex JSON response with Node.js? Properly close mongoose's connection once you're done mongodb/mongoose findMany - find all documents with IDs listed in array How to set ObjectId as a data type in mongoose