Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the connection of Mongoid

Does Mongoid has any method like ActiveRecord::Base.connected?? I want to check if the connection that's accessible.

like image 429
Zernel Avatar asked Oct 20 '22 17:10

Zernel


2 Answers

My solution:

    def check_mongoid_connection
        mongoid_config = File.read("#{Rails.root}/config/mongoid.yml")
        config = YAML.load(mongoid_config)[Rails.env].symbolize_keys
        host, db_name, user_name, password = config[:host], config[:database], config[:username], config[:password]
        port = config[:port] || Mongo::Connection::DEFAULT_PORT

        db_connection = Mongo::Connection.new(host, port).db(db_name)
        db_connection.authenticate(user_name, password) unless (user_name.nil? || password.nil?)
        db_connection.collection_names
        return { status: :ok }
    rescue Exception => e
        return { status: :error, data: { message: e.to_s } }
    end
like image 27
Zernel Avatar answered Oct 22 '22 22:10

Zernel


We wanted to implement a health check for our running Mongoid client that tells us whether the established connection is still alive. This is what we came up with:

Mongoid.default_client.database_names.present?

Basically it takes your current client and tries to query the databases on its connected server. If this server is down, you will run into a timeout, which you can catch.

like image 62
snrlx Avatar answered Oct 22 '22 20:10

snrlx