Troubleshooting Mongoose Error - MongoNetworkError: failed to connect to server [localhost:27017]

27 Views Asked by At

I am using MongoDB 4.2 and Mongoose 5.7.0 and I am getting the following error when I try to run my app.

C:\Users\Dell\Documents\23\code\newApp\node_modules\mongodb\lib\core\topologies\server.js:441
              new MongoNetworkError(
              ^
    MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED ::1:27017

I have tried changing my version of Mongoose, using a different connection URL, and configuring my firewall to allow incoming requests on port 27017, but the issue still persists.

This is my DB connection code.

const mongoose = require('mongoose');

const dbURL = 'mongodb://localhost:27017/myDatabase';

const connectDB = () => {
    mongoose.connect(dbURL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    const db = mongoose.connection;
    db.on('connected', () => {
        console.log('Connected to MongoDB');
    });
}

module.exports = connectDB;

How can I fix this error? Thanks in advance.

0

There are 0 best solutions below