[Fixed] MongoError: connect ECONNREFUSED 127.0.0.1:27017 – Node.js

Photo of author
Written By M Ibrahim
alpine-linux mongodb node.js

Quick Fix: Modify your MongoDB connection string by replacing ‘localhost’ with ‘0.0.0.0’. This commonly resolves connection issues in Node.js applications when upgrading from Node 14 to 17.

The Problem:

A Node.js application using the MongoDB package encounters the error "MongoError: connect ECONNREFUSED 127.0.0.1:27017" when attempting to connect to a local MongoDB instance. The "mongod" command works properly, but the MongoClient fails to connect. The issue persists despite having the correct MongoDB installation, granting write permissions to necessary directories, and specifying the correct database URL. Investigate the cause of the connection failure and provide a solution.

The Solutions:

Solution 2: Start MongoDB service

You may encounter the `connect ECONNREFUSED` error because the **MongoDB** service isn’t running. To start the service, follow these steps:

  1. Press Windows + R keys on your keyboard to open the Run window. Type services.msc and hit Enter. A new window will open.
  2. Locate MongoDB.exe. Right-click on it and select Start.

The MongoDB service will start. Now try running `npm start` again, and the code should work this time.

Solution 3: Don’t forget to start MongoDB

The core issue is: Some times we forget to start MongoDB.

Open the terminal and type the below command to start MongoDB:

sudo service mongod start

Solution 4: Starting MongoDB Server

To resolve the error “MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]”:

1. Open the **Run** dialog box (Windows key + R).

2. Type **services.msc** and click **OK**.

3. Locate the **MongoDB** service in the list.

4. Right-click on the **MongoDB** service and select **Start**.

Now, try running your Node.js program again. It should connect to the MongoDB server without any issues.

Solution 5: Windows Installation

For a Windows system, navigate to the MongoDB installation folder (typically C:\Program Files\MongoDB\Server\3.4\bin). Open a command prompt in this folder and execute the following command:

mongod.exe --dbpath c:\data\db

Ensure that the c:\data\db directory exists; if not, create it manually. If the directory already exists, proceed with the command.

After executing this command, MongoDB should start running successfully.