MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

Viewed 11203

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

3 Answers

If It's MAC OS, run following command and try again:

brew services restart mongodb-community

the commands that follow will be the following:

Stopping mongodb-community... (might take a while)
==> Successfully stopped mongodb-community (label: homebrew.mxcl.mongodb-community)
==> Successfully started mongodb-community (label: homebrew.mxcl.mongodb-community)

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

This error occurs when you run your node app without a server.

Fix is to run your mongodb server first then your app.

Related