Getting Error while connecting to MongoDB using Node.js

I am getting this error, please help:

<C:\AI\ai-real-estate-friend\node_modules\mongoose\lib\connection.js:755
    err = new ServerSelectionError();
          ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at _handleConnectionErrors (C:\AI\ai-real-estate-friend\node_modules\mongoose\lib\connection.js:755:11)
    at NativeConnection.openUri (C:\AI\ai-real-estate-friend\node_modules\mongoose\lib\connection.js:730:11)
    at runNextTicks (node:internal/process/task_queues:60:5)
    at listOnTimeout (node:internal/timers:538:9)
    at process.processTimers (node:internal/timers:512: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: 27239058,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\AI\ai-real-estate-friend\node_modules\mongodb\lib\cmap\connect.js:383:20)
            at Socket.<anonymous> (C:\AI\ai-real-estate-friend\node_modules\mongodb\lib\cmap\connect.js:307: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:1494: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
}
1 Like

Hi :wave: @Musa_Mazhar,

Welcome to the MongoDB Community forums :sparkles:

It seems like MongoDB is not running or is not listening on port 27017.

To troubleshoot this error, you can try:

  1. Checking if MongoDB is running and listening on the correct port.
  2. Checking if the firewall settings allow connections to the MongoDB port.
  3. Checking if the connection URL and configuration settings are correct and match the MongoDB instance.

Let us know if you need any further help!

Best,
Kushagra

Hi Kushagra,

Good day to you.

Here’s the snapshot from cmd window where it shows that MongoDB is running on port 27017. But somehow when I use the same cmd for Node.js, MongoDB gives above error.

The

part in the error message

indicates that your localhost resolve to the IPv6 address rather than the IPv4 127.0.0.1. Try replacing localhost in your connection string with 127.0.0.1.

1 Like

Hi Steevej, so i replaced the localhost in connection string with 127.0.0.1. Here’s the code for server.js file which I am trying to run in cmd using ‘npm start’

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

mongoose.connect('mongodb://localhost:127.0.0.1/ai-real-estate-friend');

const connection = mongoose.connection;
connection.once('open', () => {
  console.log('MongoDB database connection established successfully');
});

app.listen(PORT, () => {
  console.log(`Server is running on port: ${PORT}`);
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});

const listingSchema = new mongoose.Schema({
  title: String,
  description: String,
  address: String,
  city: String,
  state: String,
  zip: String,
  price: Number,
  image: String
});

const Listing = mongoose.model('Listing', listingSchema);

app.get('/api', async (req, res) => {
  try {
    const listings = await Listing.find();
    res.json(listings);
  } catch (error) {
    console.error(error);
    res.status(500).send('Server error');
  }
});

You did not.

You replaced the port 27017 with 127.0.0.1.

Okay, maybe I am doing it wrong. Can you please guide me how to to replace the port?

Thank you so much. I didn’t correct it first, then I replaced it with. It worked. Thank you.

mongoose.connect('mongodb://127.0.0.1:27017/ai-realestate-friend');
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.