MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

I used mongoose to connect my database to my app.

I got this unexpected error.

My app.js look like this

const express = require('express');
const mongoose = require('mongoose');
const authRoutes = require('./routes/authRoutes');
const cookieParser = require('cookie-parser');
const { requireAuth, checkUser } = require('./middleware/authMiddleware');
const run = require('./admin/connection');

const app = express();

// middleware
app.use(express.static('public'));
app.use(express.json());
app.use(cookieParser());

const {default : AdminBro} = require('admin-bro');
const buildAdminRouter = require('./admin/admin.router');
const options = require('./admin/admin.options');
const port = 3000;


const url = 'mongodb://localhost:27017/dbName';
let mongooseDb;
const databaseConnect = async () => {
  mongooseDb = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true })
  .then((result) => app.listen(3000))
  .catch((err) => console.log(err));

  const db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function() {
    console.log("we are connected to database");
  });
  
    const admin = new AdminBro(options)
    const router = buildAdminRouter(admin);
    app.use(admin.options.rootPath, router);

  
};
databaseConnect();

I already installed mongodb database.

I already find similar question in stackoverflow but that answers didn’t resolve my issue. Any help will be appreciated. Thanks

Answer

I faced a similar problem.Give a try to this one:

  1. Open your C drive.
  2. Make a folder named ‘data’.
  3. Make another folder inside this data folder name ‘db’.

You can see in the documentation that By default MongoDB try to search these directories, We have to create these manually

Leave a Reply

Your email address will not be published. Required fields are marked *