1

Hi I have been trying to figure this error out for two whole days, googling, reading relevant forums in here, but seems I can not solve this error to make my code to fully function. I would appreciate any help

the first bit stands for the description of the error and the later bits are the codes . Again thank you in advance.

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
C:\Users\류 광섭\Desktop\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:291
                const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
                                     ^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (C:\Users\류 광섭\Desktop\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:291:38)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  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,
        lastUpdateTime: 50395518,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\류 광섭\Desktop\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:387:20)
            at Socket.<anonymous> (C:\Users\류 광섭\Desktop\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:310:22)
            at Object.onceWrapper (node:events:628:26)
            at Socket.emit (node:events:513:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          cause: Error: connect ECONNREFUSED ::1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 27017
          },
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' }
        },
        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,
  [Symbol(errorLabels)]: Set(0) {}
}
app.js

const path = require('path');

const express = require('express');

const blogRoutes = require('./routes/blog');

const app = express();

const db = require("./data/database");

// Activate EJS view engine

app.set('view engine', 'ejs');

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

app.use(express.urlencoded({ extended: true })); // Parse incoming request bodies

app.use(express.static('public')); // Serve static files (e.g. CSS files)

app.use(blogRoutes);

app.use(function (error, req, res, next) {

  // Default error handling function

  // Will become active whenever any route / middleware crashes

  console.log(error);

  res.status(500).render('500');

});

db.connectToDatabase().then(function () {

  app.listen(3000);

});
database

const mongodb = require("mongodb");

    const MongoClient = mongodb.MongoClient;

    let database;

    async function connect() {

       const client = await MongoClient.connect("mongodb://localhost:27017");

       database = client.db("blog");

    }

    function getDb() {

        if (!database) {

            throw { message: "Database connection not establisehd!" };

        }

        return database;
Bugi
  • 41
  • 1
  • 4

3 Answers3

3

It solved when I put 127.0.0.1 instead of localhost. Thank you for all!!!

 async function connect() {
       const client = await MongoClient.connect("mongodb://127.0.0.1:27017"); 
       database = client.db("blog"); 
Bugi
  • 41
  • 1
  • 4
  • I guess this is the problem https://stackoverflow.com/questions/20345132/127-0-0-1-is-accessible-working-but-localhost-not-accessible-not-working – albert200000 Nov 02 '22 at 14:00
0

The problems shows issues with your database access in MongoDB. I would recommend that you navigate to Network Access, click on Add IP Address and Choose Access from everywhere

engjames256
  • 1
  • 1
  • 1
0

You need to start mongodb from services

EmreG
  • 19
  • 2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – DSDmark May 31 '23 at 10:24