X
X
xutegino2017-09-08 18:15:05
MongoDB
xutegino, 2017-09-08 18:15:05

How to make Express try to connect to Mongo?

If I start the server and Monga is turned off, then Express does not retry the connection and nothing works even if Monga is then turned on.

failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

Here's the error it throws when you turn it on. Nothing else. and any request, even if Monga is enabled, the server responds with a wait.
Mongoose settings set to
mongoose.connect(process.env.DATABASE, { useMongoClient: true, autoReconnect: true, reconnectTries: 30, reconnectInterval: 1000 }, )

So reconnectTries and reconnectInterval only apply if a connection has already been established? How to fix everything in my case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey, 2020-09-08
@andrey27

// node.js: 10.15.3
// express: 4.16.4
// mongoose: 5.9.6

const mongoose = require('mongoose');
let isFirstConnected = false;

mongoose.Promise = global.Promise;

function connectDB() {
  mongoose.connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
}

mongoose.connection.on('connected', () => {
  console.log(
    `Mongoose default connection open ${process.env.DATABASE}`,
  );
  isFirstConnected = true;
});

mongoose.connection.on('error', err => {
  console.log('Mongoose default connection error: ' + err);
  if (!isFirstConnected) {
    setTimeout(connectDB, 1000);
  }
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose default connection disconnected');
});

connectDB();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question