我有一个简单的 Node.js ,它使用 mongoose 连接 mLab 上托管的 Mongo 数据库。
一切似乎都运转正常:添加新记录,查询现有内容。
有时候,经过一段时间的不活动后,当我看到控制台时,我会看到以下内容:
events.js:160
throw er; // Unhandled 'error' event
^
Error: connection timeout
at Db.<anonymous> (___PATH___/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:168:17)
at emitTwo (events.js:106:13)
at Db.emit (events.js:191:7)
at Server.listener (___PATH___/node_modules/mongodb/lib/db.js:1786:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Server.<anonymous> (___PATH___/node_modules/mongodb/lib/server.js:274:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Pool.<anonymous> (___PATH___/node_modules/mongodb-core/lib/topologies/server.js:334:12)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (___PATH___/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
现在它对我来说并不重要 - 我总是可以重启应用程序。我担心在制作中会引起很多麻烦,所以我先发制人地问一下这里的问题是什么?
请注意,最初一切正常,一段时间后我得到Error: connection timeout
答案 0 :(得分:1)
使用Mongoose的Mongo-Node的示例连接代码
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const options = {
useMongoClient: true,
reconnectTries: 5000,
reconnectInterval: 0,
socketTimeoutMS: 100000,
connectTimeoutMS: 100000
}
mongoose.connect(mongodb://........, options);
var db = mongoose.connection;
db.on('error', function (error) {
console.log('Error while connecting to mongodb database:', error);
});
db.once('open', function () {
console.log('Successfully connected to mongodb database');
});
db.on('disconnected', function () {
//Reconnect on timeout
mongoose.connect(mongodb://........, options);
db = mongoose.connection;
});
答案 1 :(得分:0)
如下:
var timeout = require('connect-timeout');
app.use(timeout('5s'));`
在您的app.js
文件中
答案 2 :(得分:0)
使用以下代码替换您的猫鼬连接设置:
var mongoose = require('mongoose');
/*
* Mongoose by default sets the auto_reconnect option to true.
* We recommend setting socket options at both the server and replica set level.
* We recommend a 30 second connection timeout because it allows for
* plenty of time in most operating environments.
*/
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://user:pass@host:port/db';
mongoose.connect(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
// Wait for the database connection to establish, then start the app.
});