我有这段代码可以打开与 mongodb 的连接:
db_connect_mongo = init: (callback) ->
self = this
mongo_options = db:
safe: true
mongoose.connect DB_URL, mongo_options
db = self.db_mongo = mongoose.connection
db.on "error", (error) ->
logger.error "ERROR connecting to: " + DB_URL, logCategory
callback error, null
db.on "connected", ->
logger.info "SUCCESSFULLY connected to: " + DB_URL, logCategory
callback true, db
db.on "disconnected", ->
logger.info "DISCONNECTED from the database: " + DB_URL, logCategory
# check and connect to Redis
exports = module.exports = db_connect_mongo
然后我在我的 app.coffee 中调用它,例如:
#Connect to database
dbconnection = require "./utils/dbconnect"
dbconnection.init (result) ->
logger.info "Database initialized: " + result, logCategory
当我关闭 mongo db 时,我info: [DATABASE Connection] DISCONNECTED from the database: mongodb://127.0.0.1:27017/zmgc-mongo
在 logger.coffee 中得到一个 so,如果 mongodb 出现,我想“监听”以便建立连接。
什么是捕获所有取消/重新连接到数据库的事件的好方法?