skip to Main Content

I am trying to learn Node.JS from scratch. I am trying to connect index.js to MongoDB compass when I get the error:

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at _handleConnectionErrors (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongoose/lib/connection.js:897:11)
    at NativeConnection.openUri (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongoose/lib/connection.js:848:11) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        minRoundTripTime: 0,
        lastUpdateTime: 31356356,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
            at connectionFailureError (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongodb/lib/cmap/connect.js:353:20)
            at Socket.<anonymous> (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongodb/lib/cmap/connect.js:268:44)
            at Object.onceWrapper (node:events:635:26)
            at Socket.emit (node:events:520:28)
            at emitErrorNT (node:internal/streams/destroy:170:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
          [cause]: Error: connect ECONNREFUSED 127.0.0.1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16) {
            errno: -111,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 27017
          }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

I have used mongosh to make sure that the connection string is correct and working fine. MongoDB service is up and running.

import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";

// Create an Express app
const app = express();

// Load environment variables from .env file
dotenv.config();

// Set the port from environment variables or default to 7000
const PORT = process.env.PORT || 7000;

// Get the MongoDB connection URL from environment variables
const MONGOURL = process.env.MONGO_URL;

// Connect to MongoDB and start the server
mongoose.connect(MONGOURL).then(() => {
  console.log("Database connected successfully.");
  app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
  });

});
PORT = 8000
MONGO_URL = "mongodb://localhost:27017/dbconnect"

The setup is very basic and I have no clue on how to solve it.

I have tried using a wide variety of connection strings by using localhost, 127.0.0.1, or 0.0.0.0.

3

Answers


  1. Your MONGO_URL maybe wrong.
    The dbconnect should be your default database name.
    You can find the reference here.

    Login or Signup to reply.
  2. Your MONGO_URL is wrong. You should add correct path mongodb://localhost:27017/dbconnect.

    example :- mongodb://localhost:27017/correct path

    correct path should be add

    Login or Signup to reply.
  3. You can check the following :

    1. MongoDB is running on port 27017 (default). If you are running MongoDB on different port, kindly change the port in the connection string
    2. Ensure that there are no firewall rules or network configurations blocking access to 127.0.0.1:27017.
    3. Check mongodb logs for more insights
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search