Reputation: 628
I am currently using [email protected], whenever I manually disconnect MongoDb, mongoose disconnect/reconnect event are not fired corrected, reconnect event is fired and disconnect is not being fired every time the MongoDb is disconnect/started manually. My problem is to handle MongoDb connect and disconnected status so that for every request made to server I would see the status of the MongoDb connection/disconnection and send appropriate response(may be 500 code) because the request hangs up in middle if MongoDb is not connected. To see if this was the version issue I stated version 3.8.x and went to 4.0.4 to see where the events are fired properly. I was able to catch reconnect event from version 4.0.x but not the disconnect event. Basically wanted to know which version i can use where connect/disconnect events are fired properly or way to handle the issue.
below is the code handle events
var db = mongoose.connection;
var connected;
db.on('open', function (ref) {
connected = true;
console.log('open connection to mongo server.');
});
db.on('connected', function (ref) {
global.mongo_conn=true;
console.log('Connected connection to mongo server.');
});
db.on('disconnected', function (ref) {
connected = false;
console.log('disconnected connection.');
});
db.on('disconnect', function (err) {
console.log('Error...disconnect', err);
});
db.on('connecting', function (ref) {
connected = false;
console.log('connecting.');
});
db.on('close', function (ref) {
global.mongo_conn=false;
console.log('close connection.');
connect();
});
db.on('error', function (ref) {
connected = false;
console.log('Error connection.');
//mongoose.disconnect();
global.mongo_conn=false;
});
db.on('reconnected', function () {
global.mongo_conn=true;
console.log('MongoDB reconnected!');
});
db.on('reconnecting', function () {
global.mongo_conn=true;
console.log('reconnecting!');
});
function connect() {
mongoose.connect(config.mongo.uri, opts);
}
connect();
Upvotes: 0
Views: 3436
Reputation: 105
mongoose.connect(url,
{
server: {
auto_reconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
socketOptions: {keepAlive: 1, connectTimeoutMS: 30000}
}
}
);
Upvotes: 1