我从使用默认连接转移到明确定义的连接。
我的代码正常工作,但跟踪我的mongo连接状态的事件处理程序都没有被触发。
我使用默认mongoose连接时用于触发的事件。 (mongoose.connect)。
var mongoose = require('mongoose'),
logger = require('../logger'),
config = require('../config');
mongoose.connection.on('connecting', function(){
logger.info("trying to establish a connection to mongo");
});
mongoose.connection.on('connected', function() {
logger.info("connection established successfully");
});
mongoose.connection.on('error', function(err) {
logger.error('connection to mongo failed ' + err);
});
mongoose.connection.on('disconnected', function() {
logger.log('mongo db connection closed');
})
var gracefulExit = function() {
db.close(function(){
logger.log("mongoose connection with db " + server + 'is closing');
process.exit(0);
});
};
process.on('SIGNT', gracefulExit).on('SIGTERM', gracefulExit);
var db = mongoose.createConnection(config.get('DB_URL'));
module.exports = db;
代码的问题是
我也试过
var db = mongoose.createConnection(config.get('DB_URL'));
db.on('connecting', function(){
logger.info("trying to establish a connection to mongo");
});
但这也没有发生。
答案 0 :(得分:3)
这个片段打击对我来说很好
const connection = mongoose.createConnection(`mongodb://${process.env.MONGO_URI}`);
connection.on('connected', () => {
console.log('connected to mongodb');
});
connection.on('disconnected', () => {
console.log('connection disconnected');
});
答案 1 :(得分:1)
尝试:
mongoose.connection.on('open', function() {
logger.info("database is ready now");
});
还可以临时删除.close()
答案 2 :(得分:0)
我自己偶然发现了这个问题,发现我需要在实际连接数据库之前设置EventListeners
,就像这样(使用async / await):
export class Database {
public static connect( databaseCredentials: string ) {
return new Promise( async resolve => {
// ! The `EventListeners` is setup here.
mongoose.connection.on( "connected", () => {
logger.info( "Database has connected successfully." );
});
mongoose.connection.on( "error", (error) => {
logger.error( " Obs! There was an unexpected error connecting to the database.", error );
});
// ! The acutal connection to the database happens here.
await mongoose.connect( databaseCredentials, {
useNewUrlParser: true,
useUnifiedTopology: true,
keepAlive: true,
reconnectInterval: 500,
connectTimeoutMS: 10000,
});
resolve();
});
}
}
这与mongoose.createConnections
的工作方式也应相同。
这将产生结果(如果成功):
{ message: 'Database has connected successfully.',
level: 'info',
timestamp: '2019-10-11T15:17:16.616Z' }
我只是想插手并提出解决问题的方法,并给出代码的完整示例实现,因为上述答案并未说明您听事件的顺序。如果将mongoose.connection.on()
放在await.mongoose.connect()
下方,则不会产生EventListeners
的任何响应。
编辑:错别字
答案 3 :(得分:0)
我也遇到了这个问题,
在了解了connect()
/ createConnection()
在声明事件处理程序之前执行之后,终于解决了。
因此我的open
或connected
事件处理程序将永远不会再次调用。
所以首先声明它们,然后在尝试连接后立即声明-将解决您的问题!
例如:
try {
mongoose.connection
.on('error', err => {
console.error(err);
})
.on('open', err => {
console.log(`DB connected`);
})
await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
handleError(error);
}