Answer the question
In order to leave comments, you need to log in
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]
mongoose.connect(process.env.DATABASE, { useMongoClient: true, autoReconnect: true, reconnectTries: 30, reconnectInterval: 1000 }, )
Answer the question
In order to leave comments, you need to log in
// 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 questionAsk a Question
731 491 924 answers to any question