4

Disclaimer: Similar topics did not offer a valid solution for my problem!

  • Restarted MongoDB server (it keeps running when error occurs)
  • Using MongoDB server on windows as a service (started it manually)
  • Established the connection via MongoDB Shell CLI Package by hitting enter in the comand prompt to establish the default connection (mongodb://127.0.0.1:27017/directConnection=true&serverSelectionTimeoutMS=2000 )
  • Called npm install and npm start (my dependencies are listed below)
  • Checked that MongoDB is running
  • Checked via the windows resource monitor that the port 27017 is occupied by mongod.exe using TCP and is not restricted by the firewall
  • Checked that I am not using a VPN nor a proxy connection that could interfere.
  • Then I opened http://localhost:3000/ to which I am listening (app.listen(3000);)

However, I still get the following error:

const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);                                     ^
 
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (\node_modules\mongodb\lib\sdam\topology.js:330:38)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 536295834,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (\node_modules\mongodb\lib\cmap\connect.js:293:20)
            at Socket.<anonymous> (\node_modules\mongodb\lib\cmap\connect.js:267:22)
            at Object.onceWrapper (node:events:510:26)
            at Socket.emit (node:events:390:28)
            at emitErrorNT (node:internal/streams/destroy:164:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21)
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

My dependencies:

 "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "mongodb": "^4.0.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }

FYI: Node.js v17.0.1

Update: Here is my database.js file

const mongodb = require('mongodb');

const MongoClient = mongodb.MongoClient;

let database;

async function connectToDatabase() {
  const client = await MongoClient.connect('mongodb://localhost:27017');
  database = client.db('file-demo');
}

function getDb() {
  if (!database) {
    throw { message: 'Database not connected!' };
  }
  return database;
}

module.exports = {
  connectToDatabase: connectToDatabase,
  getDb: getDb,
};

Here is my app.js:

const path = require('path');

const express = require('express');

const userRoutes = require('./routes/users');
const db = require('./data/database');

const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));

app.use(userRoutes);

db.connectToDatabase().then(function () {
  app.listen(3000);
});
Jahn E.
  • 1,228
  • 3
  • 6
  • 21
  • 1
    The error mostly means either the MongoDB server is not started _or_ the provided connection string uri is not correct. You may want to include the connection code in the post. Are you able to connect to the database server using any of the client tools like `mongosh`, `mongo` shell or Compass? – prasad_ Nov 20 '21 at 13:50
  • @prasad_ I can interact with the database via MongoDB shell (I successfully used CRUD operations via mongosh). I updated my post with the code I use to establish a connection. – Jahn E. Nov 20 '21 at 15:24
  • 4
    Try `'mongodb://localhost:27017'` changing the `localhost` to `127.0.0.1`, in the database.js. – prasad_ Nov 20 '21 at 16:29
  • @prasad_ It worked thank you very much, post it as an answer & I will accept it for future reference. – Jahn E. Nov 20 '21 at 16:37
  • 1
    Its a common issue, and there are already detailed and well explained answers with this / similar issue. Thanks and happy coding! – prasad_ Nov 20 '21 at 16:44

4 Answers4

20

As @prasad_ pointed out, it can help to change localhost to 127.0.0.1, in the file, in which you are establishing your connection to the MongoDB Server. Although they should be treated as synonyms and as I was able to rule out the general problems (which you can find as an answer in similar questions) this might just be a caching issue with chrome, like in here.

Jahn E.
  • 1,228
  • 3
  • 6
  • 21
  • I got the same issue in my NextJS app after updating Node 14x to Node 16x. Changing `localhost` to `127.0.0.1` fixed the issue. If you are using NextJS you may have to delete the `.next` folder in the root. – kiranvj Jun 09 '23 at 05:54
8

In my case I replaced the hostname

localhost

to

127.0.0.1

Try change from

async function connectToDatabase(){
const client = await MongoClient.connect('mongodb://localhost:27017');
 database = client.db('file-demo');
}

to

async function connectToDatabase() {
 const client = await MongoClient.connect('mongodb://127.0.0.1:27017');
 database = client.db('file-demo');
}
Arafat Alim
  • 81
  • 1
  • 1
3

For me the issue was that I was not running the mongodb service after I had installed it.

On mac, run:

brew services start mongodb-community@5.0
Ian
  • 1,746
  • 1
  • 15
  • 28
0
connect like this 

     
    // MongoDB connection options
    const options = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      serverSelectionTimeoutMS: 30000, // Increased timeout value
      maxPoolSize: 50,
      wtimeoutMS: 25000,
    socketTimeoutMS: 60000,
    };
    
    const mongoURL = 'mongodb://127.0.0.1:27017/dbgstf';
const dbName = 'dbgstf';

    
    app.use(express.json());
    
    mongoose.connect(mongoURL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      serverSelectionTimeoutMS: 5000,
    })
      .then(() => {
        console.log('Database connected successfully!');
      })
      .catch((err) => {
        console.error('Error connecting to the database', err);
        process.exit(1); // Exit the application if database connection fails
      });
btm me
  • 368
  • 3
  • 11