I was very tearing my hair over this problem since I started to develop my project (12 months ago!), Always believing that I would find an answer before I was ready for release ... Unfortunately, this was not the case!
Basically, I have a pretty simple node.js server running on Azure connecting to the MongoLab database (now MLab) using mongoose.
The connection code is as follows:
mongoose.connect(envConfig.app.db, {
server: {
auto_reconnect: true,
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS : 30000,
}
},
replset: {
auto_reconnect: true,
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS : 30000,
}
}
}, function (err) {
if (err) winstonLogger.error(err);
});
mongoose.connection.on('connecting', function () {
console.log('Connecting to MongoDB...');
});
mongoose.connection.on('connected', function () {
console.log('MongoDB connected!');
});
mongoose.connection.on('open', function () {
console.log('MongoDB connection opened!');
});
mongoose.connection.on('error', function (err) {
console.error('Error in MongoDb connection: ' + err.stack);
winstonLogger.error(err);
mongoose.disconnect();
});
mongoose.connection.on('disconnected', function () {
winstonLogger.error('MongoDB disconnected!');
mongoose.connect(envConfig.app.db, {
server: {
auto_reconnect: true,
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS : 30000,
}
},
replset: {
auto_reconnect: true,
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS : 30000,
}
}
});
});
mongoose.connection.on('reconnected', function () {
console.log('MongoDB reconnected!');
});
mongoose.connection.on('close', function () {
console.log('MongoDB closed');
});
All the additional timeout options, etc. that you see are part of my attempts to fix this problem (to no avail).
Here is a typical query:
AccessToken.findOne({ token: token })
.maxTime(10000)
.exec(function (err, accessToken) {
if (err) return done(err);
});
, , . ... , , . - , ... . , . . - , - , . -, , , - :
POST /api/auth/verify - - ms - -
, - , db ( - ) .
, , , , ... ... . Azure MongoLab. . , Azure , . , Mongoose , maxTime...
MongoLab , , :
http://docs.mlab.com/connecting/#known-issues,
, , , , , .
, , .
- , ...
!