i using mongoose@4.0.4, whenever manually disconnect mongodb, mongoose disconnect/reconnect event not fired corrected, reconnect event fired , disconnect not being fired every time mongodb disconnect/started manually. problem handle mongodb connect , disconnected status every request made server see status of mongodb connection/disconnection , send appropriate response(may 500 code) because request hangs in middle if mongodb not connected. see if version issue stated version 3.8.x , went 4.0.4 see events fired properly. able catch reconnect event version 4.0.x not disconnect event. wanted know version can use connect/disconnect events fired or way handle issue.
below code handle events
var db = mongoose.connection; var connected; db.on('open', function (ref) { connected = true; console.log('open connection mongo server.'); }); db.on('connected', function (ref) { global.mongo_conn=true; console.log('connected connection 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();
mongoose.connect(url, { server: { auto_reconnect: true, reconnecttries: number.max_value, reconnectinterval: 1000, socketoptions: {keepalive: 1, connecttimeoutms: 30000} } } );
Comments
Post a Comment