Reputation: 4942
What method should I call on Mongo::Client
object to check that connection to the database server is active?
require 'mongo'
host = '127.0.0.1'
port = '27017'
client = Mongo::Client.new("mongodb://#{host}:#{port}")
Upvotes: 2
Views: 1704
Reputation: 4942
As mtj suggested, to check if connection is valid/active I am trying to get the list of databases as below:
require 'mongo'
host = '127.0.0.1'
port = '27017'
begin
client = Mongo::Client.new("mongodb://#{host}:#{port}")
client.database_names
rescue Mongo::Auth::Unauthorized, Mongo::Error => e
info_string = "Error #{e.class}: #{e.message}"
puts info_string
end
Upvotes: 2
Reputation: 3554
MongoClient in various languages is implemented as a "lazy stub", so that you will not get an immediate error, if the connection is not possible. Instead, you get the error when a concrete query goes over the line.
As far as I know, the only way to be sure that an actual connection takes place is, to query some data from the server. For example, in our project, we simply read the list of databases upon initialization.
Note: as the query results also may be lazy stubs, make sure to actually read the result in your client ;-)
Upvotes: 1